Node selectors, affinity, taints & tolerations
Place or keep Pods off specific nodes on purpose.
By Invicly Tech, , in Kubernetes Administrator (CKA). About 9 minutes to read.
In short
The scheduler filters nodes that can run a Pod, scores the rest and binds the Pod to the best one. nodeSelector and affinity attract Pods to nodes, while taints repel Pods that lack a matching toleration. Combining them lets you dedicate nodes to specific workloads.
Explained simply
When you create a Pod, it does not know where it will run yet. A component called the scheduler picks a node for it. Most of the time you let it choose freely. Sometimes you need control: a Pod needs a GPU, or a database must run on fast SSD nodes.
There are two kinds of tools. Some attract: labels on nodes plus a nodeSelector or affinity rule on the Pod say "put me there". Others repel: a taint on a node says "stay away", and only Pods with a matching toleration may come.
A toleration is like a visitor pass. It lets a Pod enter a tainted node, but it does not send the Pod there. To dedicate nodes to one team, you need both: a taint to keep others out and an affinity to pull the right Pods in.
When nothing fits, the Pod stays Pending and kubectl describe shows a clear message such as 0/3 nodes are available, with the reason for each node. Reading that line is half the job.
Press Play on a diagram to walk through it one step at a time.
- 1Pod created
spec.nodeName is empty, so it is Pending.
- 2Filter
Drop nodes lacking resources, labels or tolerations.
- 3Score
Rank nodes by spread, affinity and balance.
- 4Bind
Write the chosen node into the Pod.
- 5kubelet starts it
Node's kubelet pulls images and runs containers.
- Set on the Pod
- Pulls Pods to labeled nodes
- Required or preferred rules
- Pod anti-affinity spreads replicas
- Taint set on the node
- Repels Pods without a toleration
- NoSchedule, PreferNoSchedule, NoExecute
- Toleration allows, never forces
- On the node
- Labels
- Taints: NoSchedule, PreferNoSchedule, NoExecute
- cordon (unschedulable)
- On the Pod: attract
- nodeSelector
- nodeAffinity required or preferred
- podAffinity
- On the Pod: repel or spread
- podAntiAffinity
- topologySpreadConstraints
- On the Pod: override
- tolerations
- nodeName skips the scheduler
- priorityClassName
In depth
Node affinity syntax that actually works
requiredDuringSchedulingIgnoredDuringExecution holds nodeSelectorTerms. The terms are ORed: a node needs to match only one. Inside a term, all matchExpressions are ANDed. Operators are In, NotIn, Exists, DoesNotExist, Gt and Lt; NotIn and DoesNotExist give you anti-affinity to nodes.
preferredDuringSchedulingIgnoredDuringExecution is a list of weighted preferences, each with a weight from 1 to 100 and a preference term. The scheduler adds the weights of matching terms to a node's score, but never refuses a node for missing them. IgnoredDuringExecution means label changes after scheduling do not move running Pods.
- nodeSelector is the simple form: all labels must match
- kubectl get nodes -L disktype shows a label as a column
- Well-known labels: kubernetes.io/hostname, topology.kubernetes.io/zone
Pod affinity, anti-affinity and spreading
Pod affinity places a Pod near other Pods; anti-affinity keeps it away. Both use a labelSelector to pick the other Pods and a topologyKey to define what near means. topologyKey kubernetes.io/hostname means same node; topology.kubernetes.io/zone means same zone.
A required anti-affinity against your own app label puts each replica on a different node. If you have more replicas than nodes, the extra ones stay Pending. For softer spreading, topologySpreadConstraints is often better: maxSkew 1 with topologyKey zone keeps the Pod count per zone within one of each other, and whenUnsatisfiable chooses DoNotSchedule or ScheduleAnyway.
- At most one per node
- Extra replicas stay Pending
- Strict and simple
- Costly to evaluate at scale
- Tries one per node
- Doubles up when needed
- Never blocks scheduling
- Weight decides strength
- Even counts per domain
- maxSkew sets tolerance
- Works for zones and nodes
- Hard or soft mode
Taint effects and tolerations in detail
A taint is key=value:effect. NoSchedule blocks new Pods without a toleration. PreferNoSchedule tries to avoid the node. NoExecute also evicts running Pods that do not tolerate it; a toleration may add tolerationSeconds to stay for a limited time before eviction.
A toleration matches with operator Equal (key, value and effect must match) or Exists (no value needed). An empty key with operator Exists tolerates every taint, which is how some system DaemonSets run everywhere. Kubernetes adds taints itself: node.kubernetes.io/unschedulable when you cordon, and node.kubernetes.io/not-ready or unreachable with NoExecute when a node fails. Pods get automatic tolerations of 300 seconds for those two, which is why Pods on a dead node are replaced after about five minutes.
- kubectl describe node NAME | grep Taints
- Leave out effect in a toleration to match all effects for that key
- kubectl cordon adds the unschedulable taint; uncordon removes it
Bypassing and overruling the scheduler
Setting spec.nodeName in a Pod skips the scheduler entirely: the kubelet on that node just runs it. Taints with NoSchedule are not checked in that case, although NoExecute taints still evict the Pod. This is handy when the scheduler itself is broken, and it is a common exam trick.
PriorityClasses rank Pods. When a high-priority Pod cannot fit, the scheduler may preempt (evict) lower-priority Pods to make room. Cluster components use the built-in classes system-cluster-critical and system-node-critical. Use your own classes sparingly, or preemption can surprise other teams.
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Use nodeSelector with node labels~1h
- 2Write node affinity rules~1h
- 3Use pod affinity and anti-affinity~1h
- 4Taint nodes and add tolerations~1h
Key points
- requiredDuringScheduling is a hard rule; preferredDuringScheduling is a weighted wish.
- NoExecute also evicts running Pods that do not tolerate the taint.
- Dedicated nodes need both a taint and an affinity or nodeSelector.
- Control plane nodes carry node-role.kubernetes.io/control-plane:NoSchedule.
- Remove a taint by adding a trailing minus to the kubectl taint command.
Key terms
Tap a card to flip it. 0/5 known
Examples
kubectl label node node1 disktype=ssd
kubectl taint node node1 gpu=true:NoSchedule
# Pod spec:
# nodeSelector: { disktype: ssd }
# tolerations:
# - key: gpu
# operator: Equal
# value: "true"
# effect: NoSchedule
kubectl taint node node1 gpu=true:NoSchedule- # removeDedicate GPU nodes to the ML team
Step 1: label and taint the GPU node, so ordinary Pods stay away. Step 2: give ML Pods a toleration so they may enter, and a required node affinity so they must land there. Step 3: verify with kubectl get pods -o wide. Without the taint, other Pods would fill the GPU node; without the affinity, ML Pods could land anywhere.
# kubectl label node gpu1 hw=gpu
# kubectl taint node gpu1 hw=gpu:NoSchedule
spec:
tolerations:
- { key: hw, operator: Equal, value: gpu, effect: NoSchedule }
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- { key: hw, operator: In, values: [gpu] }
containers: [{ name: train, image: busybox:1.36, command: [sleep, "3600"] }]Reading a Pending message
A Pod is Pending on a 3-node cluster. Step 1: describe it and read the FailedScheduling event, for example: 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. Step 2: the control plane is expected to refuse. Step 3: compare the Pod's selector with real node labels; here the label was disk=ssd but the Pod asked for disktype=ssd. Step 4: fix the label or the selector.
kubectl describe pod db-0 | grep -A4 Events
kubectl get pod db-0 -o jsonpath='{.spec.nodeSelector}'
kubectl get nodes --show-labels | grep -o 'dis[a-z]*=ssd'
kubectl label node node2 disktype=ssdQuick reference
- kubectl label node n1 disktype=ssd; remove with kubectl label node n1 disktype-
- kubectl taint node n1 key=val:NoSchedule; remove by adding - at the end
- nodeSelectorTerms are ORed; matchExpressions inside one term are ANDed
- Preferred affinity weights range from 1 to 100
- topologyKey kubernetes.io/hostname means per node; topology.kubernetes.io/zone per zone
- spec.nodeName skips the scheduler completely
- Pods tolerate not-ready and unreachable taints for 300 seconds by default
Common mistakes
- Adding only a toleration and expecting the Pod to land on the tainted node.
- Typos in label keys, leaving Pods Pending with no matching nodes.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Label node01 with tier=frontend and run a Pod web that only schedules on nodes with that label.
- Exercise 2medium
Taint node01 with maintenance=true:NoExecute and keep only a Pod named keeper running there, allowed to stay for 1 hour.
- Exercise 3hard
Create Deployment cache with 3 replicas that prefers SSD nodes (weight 80) and must never put two replicas on the same node.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between nodeSelector and node affinity?
- nodeSelector is a simple exact match on labels. Node affinity adds operators like In, NotIn and Exists, OR between terms, and soft preferences with weights.
- Why do my Pods not run on the control plane node?
- kubeadm taints control plane nodes with node-role.kubernetes.io/control-plane:NoSchedule. Add a toleration for it, or remove the taint in a lab.
- Does changing a node label move running Pods?
- No. Affinity rules are IgnoredDuringExecution, so they only matter when a Pod is scheduled. Use a NoExecute taint or delete the Pods to move them.