It is used to ensure the pods are scheduled on the right nodes. It allows us to use complex logic to decide which node the pod should be scheduled on. It uses the concept of labelling nodes as seen in Node Selector.
Node Affinity Types
It defines the behaviour of the node affinity when scheduling a new pod (
DuringScheduling
) and when a pod has been running (DuringExecution
). These are of types:
required
DuringScheduling
Ignored
DuringExecution
- During pod scheduling, the node must satisfy the node affinity requirements. If none of the nodes satisfy the requirements, the pod will not be scheduled.
- A pod already running should be allowed to keep running.
preferred
DuringScheduling
Ignored
DuringExecution
- During pod scheduling, the node should ideally satisfy the node affinity requirements. If none of the nodes satisfy the requirements, the pod will still be scheduled on a node.
- A pod already running should be allowed to keep running.
required
DuringScheduling
Required
DuringExecution
(planned to be released)- During pod scheduling, the node must satisfy the node affinity requirements. If none of the nodes satisfy the requirements, the pod will not be scheduled.
- A pod already running on a node that does not satisfy the node affinity requirements will be evicted from that node.
Schedule a pod on a node with compute
label high
or medium
apiVersion: v1 kind: Pod metadata: name: web-pod spec: containers: - name: nginx image: nginx affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: compute operator: In values: - high - medium
Schedule a pod on a node with compute
label not low
apiVersion: v1 kind: Pod metadata: name: web-pod spec: containers: - name: nginx image: nginx affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: compute operator: NotIn values: - low
Schedule a pod on a node where compute
label exists
apiVersion: v1 kind: Pod metadata: name: web-pod spec: containers: - name: nginx image: nginx affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: compute operator: Exists