您可以在 cronjob 的 pod 模板部分使用Pod间反亲和性。Pod 间亲和性和反亲和性允许您根据已经在节点上运行的 pod 上的标签来限制您的 pod 有资格调度哪些节点,而不是基于节点上的标签。规则的形式是“如果 X 已经在运行一个或多个符合规则 Y 的 pod,则该 pod 应该(或者,在反亲和的情况下,不应该)在 X 中运行”</p>
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: test
spec:
schedule: "*/5 * * * *"
jobTemplate:
spec:
template:
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- web-store
topologyKey: "kubernetes.io/hostname"
containers:
- name: hello
image: bash
command: ["echo", "Hello world"]
restartPolicy: OnFailure
必要的 API 文档
kubectl explain cronjob.spec.jobTemplate.spec.template.spec.affinity.podAntiAffinity
KIND: CronJob
VERSION: batch/v1beta1
RESOURCE: podAntiAffinity <Object>
DESCRIPTION:
Describes pod anti-affinity scheduling rules (e.g. avoid putting this pod
in the same node, zone, etc. as some other pod(s)).
Pod anti affinity is a group of inter pod anti affinity scheduling rules.
FIELDS:
preferredDuringSchedulingIgnoredDuringExecution <[]Object>
The scheduler will prefer to schedule pods to nodes that satisfy the
anti-affinity expressions specified by this field, but it may choose a node
that violates one or more of the expressions. The node that is most
preferred is the one with the greatest sum of weights, i.e. for each node
that meets all of the scheduling requirements (resource request,
requiredDuringScheduling anti-affinity expressions, etc.), compute a sum by
iterating through the elements of this field and adding "weight" to the sum
if the node has pods which matches the corresponding podAffinityTerm; the
node(s) with the highest sum are the most preferred.
requiredDuringSchedulingIgnoredDuringExecution <[]Object>
If the anti-affinity requirements specified by this field are not met at
scheduling time, the pod will not be scheduled onto the node. If the
anti-affinity requirements specified by this field cease to be met at some
point during pod execution (e.g. due to a pod label update), the system may
or may not try to eventually evict the pod from its node. When there are
multiple elements, the lists of nodes corresponding to each podAffinityTerm
are intersected, i.e. all terms must be satisfied.
注意: Pod 反亲和要求节点标签一致,也就是说集群中的每个节点都必须有一个合适的标签匹配 topologyKey。如果某些或所有节点缺少指定的 topologyKey 标签,则可能导致意外行为。