Scheduling: Affinity & Anti-Affinity
Key Takeaways for AI & Readers
- Node Affinity: Attracts Pods to specific nodes based on node labels (e.g., hardware types like SSD or GPU).
- Hard vs. Soft Rules: "Required" rules must be met for a Pod to schedule, while "Preferred" rules act as a weighted suggestion.
- Inter-Pod Affinity: Co-locates related Pods (e.g., Web and Redis) on the same node to reduce network latency.
- Anti-Affinity for HA: Spreads replicas of the same application across different nodes to ensure High Availability during hardware failures.
We covered Taints and Tolerations (which repel pods from nodes). Now let's look at Affinity, which attracts pods to nodes.
Node Affinity
Allows you to constrain which nodes your pod is eligible to be scheduled on, based on labels on the node.
Node 1 (HDD)
📦
Node 2 (SSD)
📦
Node 3 (SSD)
📦
Without affinity, the pod can go anywhere.
Types of Affinity
- requiredDuringSchedulingIgnoredDuringExecution (Hard):
- "Run only on Intel CPUs."
- If no node matches, the Pod stays
Pending.
- preferredDuringSchedulingIgnoredDuringExecution (Soft):
- "Prefer SSDs, but HDD is fine if necessary."
- Kubernetes will try to find a matching node, but won't block if it can't.
Pod Affinity & Anti-Affinity
Instead of matching Node labels, you match Pod labels.
Pod Affinity (Togetherness)
- Rule: "Run this Pod on the same node as
app=redis." - Use Case: Low latency communication between a web server and its cache.
Pod Anti-Affinity (Separation)
- Rule: "Do NOT run this Pod on the same node as
app=web." - Use Case: High Availability. Ensure your 3 replicas are on 3 different nodes so one node failure doesn't kill your whole app.