Node selectors and affinity
Steering Pods with labels: nodeSelector, required and preferred node affinity, pod affinity and anti-affinity by topology, and IgnoredDuringExecution.
How the scheduler places PodsLabels, selectors, annotations and namespaces
Node selectors and affinity
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- nodeSelector is an exact-match label filter on nodes. Node affinity is the general form: operators (In, NotIn, Exists, DoesNotExist, Gt, Lt), ORed terms, and soft preferences with weights.
- Required rules are filters, and a Pod that matches no node stays Pending. Preferred rules only add to a node's score, so they can lose to other plugins.
- IgnoredDuringExecution means the rules apply at scheduling only. Relabelling a node never moves or evicts Pods already on it.
- Pod affinity and anti-affinity place Pods relative to other Pods within a topology domain named by topologyKey: same node, same zone, or anything a label defines.
- Required anti-affinity by hostname caps replicas at the node count. Prefer topology spread constraints for spreading, and keep inter-pod rules few, because they're the costliest to evaluate.
Not every node is the same
A cluster usually isn’t uniform. Some nodes have GPUs, some fast local NVMe, some are spot instances, some sit in a particular zone or run ARM. And some Pods relate to each other: replicas of one service should be on different machines, while a cache wants to be near its clients. The scheduler only knows about these things through labels: on nodes, and on Pods.
Every node carries well-known labels out of the box: kubernetes.io/hostname, kubernetes.io/os, kubernetes.io/arch, and on clouds topology.kubernetes.io/zone, topology.kubernetes.io/region and node.kubernetes.io/instance-type. Admins add their own, such as disktype=ssd. For the examples below our lab cluster had three fake nodes: n1 (zone eu-a, disktype=ssd), n2 (zone eu-b, disktype=hdd) and n3 (zone eu-a, disktype=ssd, gpu=true).
nodeSelector
The simplest tool is an exact label match:
spec:
nodeSelector: {disktype: ssd}
Only nodes with every listed label pass. Our two nodeSelector Pods went to n1. n3 also matched, but scoring preferred n1. A Pod whose selector matches nothing stays Pending with didn't match Pod's node affinity/selector.
Node affinity
Node affinity is the general version, with two kinds of rule:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- {key: gpu, operator: DoesNotExist}
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 80
preference:
matchExpressions:
- {key: disktype, operator: In, values: [ssd]}
The required part is a filter: keep GPU nodes for GPU work. The preferred part is a score: among the rest, favour SSD nodes, with a weight from 1 to 100 that feeds the NodeAffinity score plugin. Our four Pods with these rules all landed on n1, the one SSD node without a GPU. A preference is only one input among several, though. On a busy cluster, a less-loaded HDD node can still win.
Operators are In, NotIn, Exists, DoesNotExist, Gt and Lt (numeric comparison of the label value). Combining is the bit to get right: terms are ORed, expressions within a term are ANDed. A nodeSelector alongside affinity must also match.
The long names say when the rules apply. IgnoredDuringExecution means just that. We relabelled n1 to disktype=hdd while our nodeSelector: {disktype: ssd} Pods were on it, and they stayed. Nothing re-checks placement later. To move Pods, delete them, or use the descheduler project. Taints with NoExecute are the one built-in way to push running Pods off a node, covered next.
Pod affinity and anti-affinity
Sometimes the constraint is about other Pods. Pod affinity says “put me in the same domain as Pods matching this selector”. Anti-affinity says “not in the same domain”. The domain is set by topologyKey, a node label: kubernetes.io/hostname means per node, topology.kubernetes.io/zone per zone.
Keep a cache in the same zone as the Pods it serves:
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector: {matchLabels: {app: web}}
topologyKey: topology.kubernetes.io/zone
Our zone-1 Pod required a zone that ran an app=sel Pod. They were on n1 in eu-a, and the scheduler put it on n3, also in eu-a. Same zone, different node, which is the point of choosing the topology key.
Spread replicas so one node failure doesn’t take them all:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector: {matchLabels: {app: ha}}
topologyKey: kubernetes.io/hostname
That’s a hard cap. Four replicas on three nodes went one per node, and the fourth stayed Pending:
0/3 nodes are available: 3 node(s) didn't match pod anti-affinity rules.
It also bites during rolling updates: with maxSurge, the surge Pod may have nowhere to go. Use preferredDuringScheduling anti-affinity for “spread if you can”, or better, topology spread constraints, which express “at most one more here than there” and handle that case properly.
Two refinements matter in practice. Selectors usually match every version of a workload, so during a rollout new Pods are repelled by old ones. matchLabelKeys: [pod-template-hash] (GA since 1.33) adds the Pod’s own value of that label to the selector, so a Deployment’s new ReplicaSet only spreads against itself. And inter-pod affinity is the most expensive thing the scheduler evaluates, since every candidate node needs a look at the Pods in its domain. Use it for a few critical rules, not as a default in every chart.
Picking the right tool
- Needs special hardware or a particular zone: required node affinity (or
nodeSelector). - Should prefer some nodes: preferred node affinity.
- Must keep everything else off special nodes: taints, the next lesson. Affinity attracts. It doesn’t repel other Pods.
- Replicas spread for availability: topology spread constraints.
- Co-location with, or separation from, specific other Pods: pod affinity or anti-affinity.
About the video
The embed is the first 10 minutes, 0:00 to 9:44, of Anton Putra’s “Kubernetes Node Selector vs Node Affinity vs Pod Affinity vs Tains & Tolerations”, July 2023. The clip covers nodeSelector, node affinity, pod anti-affinity and pod affinity with worked examples. The video’s last chapter on taints is left for the next lesson. It doesn’t cover matchLabelKeys. Judged from chapters, since transcripts can’t be fetched here, and from its “English (US) original” audio track. Piyush’s CKA episode in deeper spends 27 minutes on node affinity alone, with operator demos.
What was run: against a local v1.37.3 control plane with three labelled fake Nodes and the real scheduler, we placed the nodeSelector, required-plus-preferred node affinity, pod affinity and anti-affinity Pods above, saw the fourth anti-affinity replica refused, and relabelled a node under running Pods to see IgnoredDuringExecution. No containers ran, checked 2026-11-29.
Where this fits
Affinity pulls Pods toward nodes. The opposite force, nodes pushing Pods away, is next: taints and tolerations.
Check yourself
A node affinity has two nodeSelectorTerms, and the first term has two matchExpressions. How are they combined?
Terms are ORed and the expressions inside one term are ANDed. A node qualifies if it satisfies every expression of at least one term. (nodeSelector, if also set, is ANDed with the affinity.).
You relabel a node from disktype=ssd to hdd. Pods on it required disktype=ssd. What happens to them?
Nothing. The rule is requiredDuringSchedulingIgnoredDuringExecution: it was checked when they were scheduled and is ignored afterwards. Only new Pods, or replacements, avoid the node.
A 4-replica Deployment uses required pod anti-affinity on kubernetes.io/hostname, and the cluster has 3 nodes. What happens?
Three Pods schedule, one per node, and the fourth stays Pending with 'didn't match pod anti-affinity rules'. During a rolling update with maxSurge, the surge Pod can be stuck the same way. Use preferred anti-affinity or topologySpreadConstraints if more replicas than nodes must be allowed.
How do you keep a cache Pod in the same zone as the web Pods it serves, without forcing it onto the same node?
Pod affinity with a labelSelector for the web Pods and topologyKey topology.kubernetes.io/zone. The scheduler only places the cache in a zone that already runs a matching Pod; any node in that zone qualifies.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.