Pod Affinity Fundamentals
What You'll Learn
You'll learn how to use pod affinity to schedule pods onto the same nodes as other pods based on their labels, creating logical co-location rules.
The Core Concept
While node affinity helps you place pods on specific nodes, pod affinity lets you place pods near other pods. Think of it like seating arrangements at a conference: node affinity is choosing which room to sit in, while pod affinity is choosing to sit near colleagues you're working with.
Pod affinity examines the labels of already-running pods to make scheduling decisions. When you define pod affinity rules, you're essentially saying: "Schedule my pod on the same node (or in the same zone/region) as pods that match these label selectors."
Why Use Pod Affinity?
Common scenarios include:
- Performance: Co-locating a web frontend with its cache service to minimize network latency
- Data locality: Keeping pods that share data on the same node to avoid cross-node traffic
- Service dependencies: Grouping tightly-coupled microservices together
How It Works
Pod affinity rules specify:
- A label selector to match target pods
- A topology key (like
kubernetes.io/hostnamefor same-node placement) - Whether the rule is required or preferred
The scheduler scans existing pods, finds those matching your selector, checks their node labels for the topology key, and places your new pod accordingly.
Unlike node affinity (which is static), pod affinity is dynamic—it depends on the current state of running pods in your cluster.
Key Takeaway: Pod affinity co-locates pods based on labels of already-running pods, enabling you to optimize for performance, data locality, and service relationships by controlling which pods run near each other.