Room 34
NODE AFFINITY
The Magnetic Fields
- Node affinity attracts pods to specific nodes based on labels. Anti-affinity pushes them apart.
- Schedule pods using affinity rules to find the password.
📜 Mission Briefing
- Label a worker node:
kubectl label node WORKER disk=ssd. - Deploy
affinity-pod.yaml- usesrequiredDuringSchedulingIgnoredDuringExecutionto targetdisk=ssdnodes. - Verify the pod lands on the labeled node.
- Use pod anti-affinity to ensure two pods DON’T co-locate.
- The affinity pod logs the password:
affinity.
Key Commands
| Command | Purpose |
|---|---|
kubectl label node NODE key=value |
Label a node |
kubectl get nodes --show-labels |
View node labels |
kubectl get pods -o wide |
See node placement |
Node Affinity & Anti-Affinity
apiVersion: v1
kind: Pod
metadata:
name: ssd-pod
spec:
affinity:
nodeAffinity:
# HARD requirement - must match
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: disk
operator: In
values: ["ssd", "nvme"]
# SOFT preference - try to match
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 80
preference:
matchExpressions:
- key: zone
operator: In
values: ["us-west-1"]
containers:
- name: app
image: busybox
command: ['sh', '-c', 'echo affinity && sleep 3600']
# Pod anti-affinity: spread pods across nodes
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 3
template:
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values: ["web"]
topologyKey: "kubernetes.io/hostname" # One per node
# Operators: In, NotIn, Exists, DoesNotExist, Gt, Lt
# nodeSelector (simpler alternative)
spec:
nodeSelector:
disk: ssd
# Node affinity vs nodeSelector:
# nodeSelector: simple key=value matching
# nodeAffinity: expressive rules with AND/OR, soft/hard, operators
Hints
Hint 3
The password is affinity.