Skip to content
LF Cert Trainer

Lesson 31 · Section 3: Scheduling

Lesson 31: Node affinity: rules for which nodes a Pod may use

What node affinity adds to nodeSelector, how required and preferred rules work inside the scheduler, how terms, expressions and operators combine, and how to write and debug affinity rules quickly in the exam. · 20 min read · 5 min video

1/12Node affinity
0:00 / 4:32

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why node affinity exists

In the previous lesson you sent a Pod to a group of nodes with nodeSelector: label the node, name the label in the Pod. That works, but nodeSelector knows a single sentence: this label must have exactly this value. Real placement rules are often richer:

  • "Run on a large or medium node."
  • "Run anywhere except on small nodes."
  • "Run on any node that has a gpu label, whatever the value."
  • "Run in zone a if you can, and somewhere else if you cannot."

None of these can be written with nodeSelector. Node affinity is the same idea (a rule in the Pod that is compared with node labels) with a richer language: operators, alternatives, and rules that are only a preference.

A rule on the Pod, labels on the nodespendingmatchmatchno matchPod reportsize In large, mediumkube-schedulerNodeAffinity pluginnode-1size=large: allowednode-2size=medium: allowednode-3size=small: rejected
A rule on the Pod, labels on the nodes. Node affinity lives in the Pod spec and is compared with node labels. Here the rule accepts two values, which a plain nodeSelector cannot express.

Parts:

  • Pod report (size In large, medium)
  • kube-scheduler (NodeAffinity plugin)
  • node-1 (size=large: allowed)
  • node-2 (size=medium: allowed)
  • node-3 (size=small: rejected)

Connections:

  • Pod report to kube-scheduler: pending
  • kube-scheduler to node-1: match
  • kube-scheduler to node-2: match
  • kube-scheduler to node-3: no match
nodeSelectorNode affinity
Wherespec.nodeSelectorspec.affinity.nodeAffinity
ComparesLabel equals valueIn, NotIn, Exists, DoesNotExist, Gt, Lt
Several conditionsAll must match (AND)AND inside a term, OR between terms
Soft rulesNoYes, with weights
LengthOne lineTen lines or more

nodeSelector is not deprecated, and for "exactly this label" it is still the quickest tool. If a Pod has both nodeSelector and node affinity, a node must satisfy both.

The two types

Node affinity has two fields, and their long names are really two short sentences glued together:

FieldDuring schedulingDuring execution
requiredDuringSchedulingIgnoredDuringExecutionRequired: no matching node, no scheduling. The Pod stays Pending.Ignored: label changes do not touch a running Pod.
preferredDuringSchedulingIgnoredDuringExecutionPreferred: matching nodes get extra points; without one, the Pod runs elsewhere.Ignored: the same.

You can use one, the other, or both in the same Pod.

A required rule

apiVersion: v1
kind: Pod
metadata:
  name: report
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
          - matchExpressions:
              - key: size
                operator: In
                values: ["large", "medium"]
  containers:
    - name: report
      image: nginx:1.29-alpine

Read it from the inside out. One expression is a key, an operator and, for most operators, a list of values: "the label size is large or medium". Expressions are grouped into a term (matchExpressions), and terms are listed under nodeSelectorTerms.

A preferred rule

spec:
  affinity:
    nodeAffinity:
      preferredDuringSchedulingIgnoredDuringExecution:
        - weight: 80
          preference:
            matchExpressions:
              - key: topology.kubernetes.io/zone
                operator: In
                values: ["zone-a"]
        - weight: 20
          preference:
            matchExpressions:
              - key: disktype
                operator: In
                values: ["ssd"]

The preferred type is a list of entries, each with a weight from 1 to 100 and one preference. A node in zone a earns 80 points, an SSD node earns 20, and an SSD node in zone a earns 100.

Operators

OperatorThe node matches whenvalues
InThe label's value is one of the listed valuesOne or more
NotInThe label's value is not in the list, or the node does not have the labelOne or more
ExistsThe node has a label with this key, whatever its valueMust be left out
DoesNotExistThe node has no label with this keyMust be left out
GtThe label's value, read as a whole number, is greater than the valueExactly one
LtThe label's value, read as a whole number, is less than the valueExactly one

Three details save you from surprises:

  • Values are always strings. Label values are strings, so write values: ["8"], not values: [8]. The same goes for words YAML treats specially, such as "true" and "yes".
  • NotIn also matches unlabelled nodes. "Not small" is true for a node that has no size label at all. If you mean "has a size, and it is not small", add an Exists expression to the same term.
  • There is no node anti-affinity field. You keep a Pod away from nodes with NotIn and DoesNotExist. (Pods do have a separate podAntiAffinity, which is about other Pods, not about nodes.)

How terms and expressions combine

How terms and expressions combineeitherorANDANDonlyRequired rulenodeSelectorTermsTerm 1matchExpressionsTerm 2matchExpressionsdisktype In ssdmust be truezone In a, band must be truegpu Existsenough on its own
How terms and expressions combine. A node passes if it satisfies any one term. To satisfy a term, it must satisfy every expression inside that term.

Parts:

  • Required rule (nodeSelectorTerms)
  • Term 1 (matchExpressions)
  • Term 2 (matchExpressions)
  • disktype In ssd (must be true)
  • zone In a, b (and must be true)
  • gpu Exists (enough on its own)

Connections:

  • Required rule to Term 1: either
  • Required rule to Term 2: or
  • Term 1 to disktype In ssd: AND
  • Term 1 to zone In a, b: AND
  • Term 2 to gpu Exists: only
requiredDuringSchedulingIgnoredDuringExecution:
  nodeSelectorTerms:
    - matchExpressions:                 # term 1: both expressions must be true
        - key: disktype
          operator: In
          values: ["ssd"]
        - key: topology.kubernetes.io/zone
          operator: In
          values: ["zone-a", "zone-b"]
    - matchExpressions:                 # term 2: an alternative
        - key: gpu
          operator: Exists

There are three levels, and each one combines differently:

LevelCombined withIn the example
Entries of nodeSelectorTermsOR: one matching term is enoughSSD in zone a or b, or any GPU node
Entries of one matchExpressionsAND: all must be trueSSD and zone a or b
Entries of one values list (In)OR: any one valuezone a or zone b

In YAML the difference between AND and OR is a single dash. A new - key: adds an expression to the same term (AND). A new - matchExpressions: starts another term (OR).

Under the hood · matchFields, and how DaemonSets use it

A term may also carry matchFields, which compares node fields instead of labels. Only one field is supported: metadata.name. That makes it possible to name nodes without relying on a label:

nodeSelectorTerms:
  - matchFields:
      - key: metadata.name
        operator: In
        values: ["node-2"]

This is exactly what the DaemonSet controller writes into each of its Pods, one Pod per node, each with that node's name. Unlike spec.nodeName, the Pod still goes through the scheduler, so taints, cordons and free resources are all checked.

In practice the label kubernetes.io/hostname does the same job with matchExpressions, and it is what you will see in most examples.

How it works inside the scheduler

Required filters, preferred scorespending2 passrejected0 points80: bindPod reportneeds ssd, likes zone aFilterrequired rulesScorepreferred weightsnode-1hdd: filtered outnode-2ssd, zone b: +0node-3ssd, zone a: +80
Required filters, preferred scores. A required rule removes nodes. A preferred rule only adds points to the nodes that are left, so the Pod is still scheduled when no node earns them.

Parts:

  • Pod report (needs ssd, likes zone a)
  • Filter (required rules)
  • Score (preferred weights)
  • node-1 (hdd: filtered out)
  • node-2 (ssd, zone b: +0)
  • node-3 (ssd, zone a: +80)

Connections:

  • Pod report to Filter: pending
  • Filter to Score: 2 pass
  • Filter to node-1: rejected
  • Score to node-2: 0 points
  • Score to node-3: 80: bind

The scheduler places each Pod in two phases, and one plugin, NodeAffinity, takes part in both:

  1. Filter. For every node, the plugin checks the Pod's nodeSelector and its required affinity. A node that fails is out, for this Pod only. If every node is out, the scheduler records a FailedScheduling event and the Pod waits as Pending.
  2. Score. For every node that passed, the plugin adds up the weight of each preferred entry the node satisfies. That sum is scaled and added to the scores of the other scoring plugins (free resources, spreading, image already present, and so on). The node with the highest total wins.

Two consequences follow from that design:

  • A preference is not a promise. Node affinity is one voice among several scoring plugins. A matching node usually wins, but a much emptier node without the label can still come out on top. If the Pod must land on a kind of node, use a required rule.
  • Weights only matter relative to each other. A single preferred entry behaves the same with weight 1 or 100. Weights start to matter when a Pod has several preferences that pull towards different nodes.

"Ignored during execution"

Affinity is evaluated at scheduling time and never again. If you remove the label size=large from a node, the Pods that were placed there because of it keep running. Nothing in Kubernetes re-checks them. There is no "required during execution" type in the API today, so node affinity cannot evict anything; eviction by node property is what NoExecute taints are for.

A parked Pending Pod, on the other hand, reacts to labels straight away. Add the missing label to a node and the scheduler retries the Pod within seconds. You do not need to delete or recreate it.

Under the hood · Affinity added by a scheduler profile

A cluster administrator can attach an affinity to a whole scheduler profile. Every Pod scheduled by that profile must then satisfy it in addition to its own rules, and the extra rule is not visible in the Pod spec:

apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
  - schedulerName: default-scheduler
  - schedulerName: batch-scheduler
    pluginConfig:
      - name: NodeAffinity
        args:
          addedAffinity:
            requiredDuringSchedulingIgnoredDuringExecution:
              nodeSelectorTerms:
                - matchExpressions:
                    - key: pool
                      operator: In
                      values: ["batch"]

If a Pod with a custom schedulerName is rejected for "node affinity" although its own spec has none, this is the place to look. Scheduler profiles have their own lesson later in this section.

Using it

Example · Require a labelled node for a Deployment

The task: "Deployment blue, 3 replicas, image nginx:1.29-alpine, must only run on nodes labelled color=blue. Label node-1 accordingly."

Label the node, then generate the Deployment and add the affinity to the Pod template:

kubectl label node node-1 color=blue
kubectl create deployment blue --image=nginx:1.29-alpine --replicas=3 --dry-run=client -o yaml > blue.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: blue
spec:
  replicas: 3
  selector:
    matchLabels:
      app: blue
  template:
    metadata:
      labels:
        app: blue
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
              - matchExpressions:
                  - key: color
                    operator: In
                    values: ["blue"]
      containers:
        - name: nginx
          image: nginx:1.29-alpine
kubectl apply -f blue.yaml
kubectl get pods -l app=blue -o wide        # all three on node-1

affinity sits at the same level as containers, under spec.template.spec. Placed one level higher, under the Deployment's own spec, it is rejected as an unknown field.

Example · Any node that has the label, whatever its value

"Run the Pod on a node that has a gpu label." The value does not matter, so use Exists and leave values out:

affinity:
  nodeAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
      nodeSelectorTerms:
        - matchExpressions:
            - key: gpu
              operator: Exists

The same pattern places a Pod on control plane nodes, whose role label has an empty value:

            - key: node-role.kubernetes.io/control-plane
              operator: Exists

On a kubeadm cluster that Pod also needs a toleration for the control plane taint. Affinity chooses the node; it does not get the Pod past a taint.

Example · Keep a Pod away from some nodes

"The Pod must not run on nodes labelled size=small, and should prefer nodes with an SSD."

affinity:
  nodeAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
      nodeSelectorTerms:
        - matchExpressions:
            - key: size
              operator: NotIn
              values: ["small"]
    preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 50
        preference:
          matchExpressions:
            - key: disktype
              operator: In
              values: ["ssd"]

Nodes with size=large, size=medium and nodes with no size label all pass the filter. Among them, SSD nodes get 50 extra points. If no node has an SSD, the Pod is scheduled all the same.

Example · Find out why an affinity Pod is Pending

kubectl describe pod report | tail -n 4
Warning  FailedScheduling  default-scheduler  0/3 nodes are available: 1 node(s) had untolerated taint
{node-role.kubernetes.io/control-plane: }, 2 node(s) didn't match Pod's node affinity/selector.

Two workers did not match the rule. Put the rule and the labels side by side:

kubectl get pod report -o jsonpath='{.spec.affinity.nodeAffinity}{"\n"}{.spec.nodeSelector}{"\n"}'
kubectl get nodes -L size                   # one column per label key
kubectl get nodes --show-labels             # everything, when you do not know the key
NAME           STATUS   ROLES           SIZE
controlplane   Ready    control-plane
node-1         Ready    <none>          Large
node-2         Ready    <none>

The rule asks for large, the node says Large. Labels are case sensitive. Fix whichever side is wrong:

kubectl label node node-1 size=large --overwrite
kubectl get pod report -o wide              # scheduled a few seconds later, no restart needed

Tricks

Common mistakes

  • Giving the preferred type the required type's shape. nodeSelectorTerms belongs only under required. Preferred is a list of weight and preference.
  • Putting values on Exists or DoesNotExist. The API server rejects it. These two operators look only at the key.
  • Unquoted numbers and booleans in values. values: [8] and values: [true] fail validation, because every value must be a string.
  • Putting the block in the wrong place in a Deployment. It goes in the Pod template (spec.template.spec), not under the Deployment's spec.
  • Expecting a label change to move running Pods. IgnoredDuringExecution means what it says. After changing labels, kubectl rollout restart deployment <name> reschedules the Pods against the new labels.
  • Using affinity to reserve nodes. Affinity pulls your Pod to the nodes; it does nothing to keep other Pods off them. Dedicated nodes need a taint as well, which is the subject of the next lesson.
  • Forgetting the node side. A perfect rule still leaves the Pod Pending if no node carries the label. Label the node first, and check with kubectl get nodes -L <key>.

Recap

  • Node affinity lives in spec.affinity.nodeAffinity and matches node labels, like nodeSelector with a richer language.
  • requiredDuringScheduling... is a filter: no matching node means Pending. preferredDuringScheduling... is a score with weights from 1 to 100: no matching node means the Pod runs elsewhere.
  • Terms in nodeSelectorTerms are ORed; expressions in one matchExpressions are ANDed.
  • Operators: In, NotIn, Exists, DoesNotExist, Gt, Lt. Values are strings.
  • Rules are checked at scheduling time only. Running Pods are never moved or evicted by a label change.
  • Pending with "didn't match Pod's node affinity/selector": compare the rule with kubectl get nodes -L <key>.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Keep a workload out of one zone with a required node affinity rule, and steer another towards the GPU node with a preference that never leaves it waiting.

    Build · Level 2 · standard · target 15 min

  • Two workloads wait because their node affinity rules match no node. Read the rules the way the scheduler does and repair them without touching the nodes.

    Fix · Level 3 · challenge · target 18 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.