Kubernetes anti-affinity rule to spread Deployment Pods to at least 2 nodes
I think I found a solution to your problem. Look at this example yaml file:
spec: topologySpreadConstraints: - maxSkew: 1 topologyKey: kubernetes.io/hostname whenUnsatisfiable: DoNotSchedule labelSelector: matchLabels: example: app affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: kubernetes.io/hostname operator: In values: - worker-1 - worker-2 preferredDuringSchedulingIgnoredDuringExecution: - weight: 50 preference: matchExpressions: - key: kubernetes.io/hostname operator: In values: - worker-1
Idea of this configuration:I'm using nodeAffinity here to indicate on which nodes pod can be placed:
- key: kubernetes.io/hostname
and
values:- worker-1- worker-2
It is important to set the following line:
- maxSkew: 1
According to the documentation:
maxSkew describes the degree to which Pods may be unevenly distributed. It must be greater than zero.
Thanks to this, the difference in the number of assigned feeds between nodes will always be maximally equal to 1.
This section:
preferredDuringSchedulingIgnoredDuringExecution: - weight: 50 preference: matchExpressions: - key: kubernetes.io/hostname operator: In values: - worker-1
is optional however, it will allow you to adjust the feed distribution on the free nodes even better. Here you can find a description with differences between: requiredDuringSchedulingIgnoredDuringExecution
and preferredDuringSchedulingIgnoredDuringExecution
:
Thus an example of
requiredDuringSchedulingIgnoredDuringExecution
would be "only run the pod on nodes with Intel CPUs" and an examplepreferredDuringSchedulingIgnoredDuringExecution
would be "try to run this set of pods in failure zone XYZ, but if it's not possible, then allow some to run elsewhere".