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
Official competency this lesson covers
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
gpulabel, 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.
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
nodeSelector | Node affinity | |
|---|---|---|
| Where | spec.nodeSelector | spec.affinity.nodeAffinity |
| Compares | Label equals value | In, NotIn, Exists, DoesNotExist, Gt, Lt |
| Several conditions | All must match (AND) | AND inside a term, OR between terms |
| Soft rules | No | Yes, with weights |
| Length | One line | Ten 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:
| Field | During scheduling | During execution |
|---|---|---|
requiredDuringSchedulingIgnoredDuringExecution | Required: no matching node, no scheduling. The Pod stays Pending. | Ignored: label changes do not touch a running Pod. |
preferredDuringSchedulingIgnoredDuringExecution | Preferred: 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
| Operator | The node matches when | values |
|---|---|---|
In | The label's value is one of the listed values | One or more |
NotIn | The label's value is not in the list, or the node does not have the label | One or more |
Exists | The node has a label with this key, whatever its value | Must be left out |
DoesNotExist | The node has no label with this key | Must be left out |
Gt | The label's value, read as a whole number, is greater than the value | Exactly one |
Lt | The label's value, read as a whole number, is less than the value | Exactly one |
Three details save you from surprises:
- Values are always strings. Label values are strings, so write
values: ["8"], notvalues: [8]. The same goes for words YAML treats specially, such as"true"and"yes". NotInalso matches unlabelled nodes. "Not small" is true for a node that has nosizelabel at all. If you mean "has a size, and it is not small", add anExistsexpression to the same term.- There is no node anti-affinity field. You keep a Pod away from nodes with
NotInandDoesNotExist. (Pods do have a separatepodAntiAffinity, which is about other Pods, not about nodes.)
How terms and expressions combine
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:
| Level | Combined with | In the example |
|---|---|---|
Entries of nodeSelectorTerms | OR: one matching term is enough | SSD in zone a or b, or any GPU node |
Entries of one matchExpressions | AND: all must be true | SSD and zone a or b |
Entries of one values list (In) | OR: any one value | zone 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
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:
- Filter. For every node, the plugin checks the Pod's
nodeSelectorand its required affinity. A node that fails is out, for this Pod only. If every node is out, the scheduler records aFailedSchedulingevent and the Pod waits asPending. - Score. For every node that passed, the plugin adds up the
weightof 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.
nodeSelectorTermsbelongs only under required. Preferred is a list ofweightandpreference. - Putting
valuesonExistsorDoesNotExist. The API server rejects it. These two operators look only at the key. - Unquoted numbers and booleans in
values.values: [8]andvalues: [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'sspec. - Expecting a label change to move running Pods.
IgnoredDuringExecutionmeans 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
Pendingif no node carries the label. Label the node first, and check withkubectl get nodes -L <key>.
Recap
- Node affinity lives in
spec.affinity.nodeAffinityand matches node labels, likenodeSelectorwith a richer language. requiredDuringScheduling...is a filter: no matching node meansPending.preferredDuringScheduling...is a score with weights from 1 to 100: no matching node means the Pod runs elsewhere.- Terms in
nodeSelectorTermsare ORed; expressions in onematchExpressionsare 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.