Node Affinity

Node affinity provides advance functionality to place pods on nodes selectively.

We can provide quite complicated conditions to decide where the pod can be scheduled.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: blue
spec:
  replicas: 3
  selector:
    matchLabels:
      run: nginx
  template:
    metadata:
      labels:
        run: nginx
    spec:
      containers:
      - image: nginx
        imagePullPolicy: Always
        name: nginx
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: color
                operator: In
                values:
                - blue

This makes sure that the pod is scheduled on the node with label color=blue.

There can different operators be used such as In, NotIn, Exists etc.

Node affinity policies

There are two main policies:

  1. requiredDuringSchedulingIgnoredDuringExecution
  2. preferredDuringSchedulingIgnoredDuringExecution

requiredDuringScheduling... requires nodes to match with pods specified selection criteria, during scheduling. While, in preferredDuringScheduling scheduler tries best to put the pod in the right node based on criteria.

...IgnoredDuringExecution ignores the selection for execution.

Note

There is one additional planned policy, requiredDuringSchedulingRequiredDuringExecution. This is not present as of now, maybe introduce in later versions of kubernetes.

...RequiredDuringExecution requires selection criteria should be satisfied even in pods are running in node. If specified labels of node are changed and do not match with pod affinity selection criteria, pods will be terminated.