What is the difference between Node Affinity and Taints/Tolerations?
❓ Interview Prompt: Compare Node Affinity (pod attraction), Taints (node repulsion), and Tolerations (pod exception) for advanced Kubernetes scheduling control.
Kubernetes scheduling has three mechanisms for controlling where Pods run:
1. Node Selector (Simple):
nodeSelector: diskType: ssd — schedule Pod only on nodes with that label. Simple but limited.
2. Node Affinity (Flexible Attraction):
Node Affinity is an expressive way to attract Pods to specific nodes based on node labels. Two types:
3. Taints (Node Repulsion — Node-Side):
A Taint is applied to a node to repel most Pods. Format: key=value:Effect.
4. Tolerations (Pod Exception — Pod-Side):
A Toleration on a Pod allows it to be scheduled on tainted nodes. Tolerations don't attract pods — they merely permit.
Common Pattern: Dedicated GPU Nodes:
Taint GPU nodes: kubectl taint node gpu-node-1 gpu=true:NoSchedule. Only GPU workload pods with matching tolerations will be scheduled there.
Code Implementation Example
# Taint a GPU node (repels all pods without toleration)
# kubectl taint nodes gpu-node-1 gpu=true:NoSchedule
spec:
# Toleration: allow this pod to schedule on tainted GPU nodes
tolerations:
- key: "gpu"
operator: "Equal"
value: "true"
effect: "NoSchedule"
# Node Affinity: REQUIRE a node with GPU label (hard requirement)
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: accelerator
operator: In
values:
- nvidia-a100 # must have this GPU type
# Prefer us-east-1a zone (soft preference)
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: topology.kubernetes.io/zone
operator: In
values:
- us-east-1aTaints repel pods from nodes (node-side); Tolerations create exceptions (pod-side). Node Affinity attracts pods to nodes. Use together for dedicated workload isolation (GPU, spot, high-memory nodes).