Skip to main content

podAffinity_podAntiAffinity_Example

podAffinity/podAntiAffinity Examples

podAffinity

An example of affinity and podAffinity settings can be seen below. This also requires a particular label to be matched when the Pod starts, but not required if the label is later removed.

spec:
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: security
operator: In
values:
- S1
topologyKey: topology.kubernetes.io/zone

Inside the declared topology zone, the Pod can be scheduled on a node running a Pod with a key label of security and a value of S1. If this requirement is not met, the Pod will remain in a Pending state.

podAntiAffinity

With podAntiAffinity, we can prefer to avoid nodes with a particular label. In this case, the scheduler will prefer to avoid a node with a key set to security and value of S2.

podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: security
operator: In
values:
- S2
topologyKey: kubernetes.io/hostname

In a large, varied environment, there may be multiple situations to be avoided. As a preference, this setting tries to avoid certain labels, but will still schedule the Pod on some node. As the Pod will still run, we can provide a weight to a particular rule. The weights can be declared as a value from 1 to 100. The scheduler then tries to choose, or avoid the node with the greatest combined value.