Pod Affinity in Kubernetes: What It Is and How It Works
pod affinity lets you tell the system to place pods close to other pods based on labels. It helps pods run on the same or nearby nodes to improve communication or resource sharing.How It Works
Pod affinity is like asking Kubernetes to seat friends together at a dinner table. You define rules that say, "Put this pod near pods with certain labels." Kubernetes then tries to schedule pods on nodes where those other pods already run.
This helps pods that need to talk a lot or share resources stay close, reducing network delays and improving performance. If the preferred nodes are full or unavailable, Kubernetes may schedule pods elsewhere, but it tries to honor your affinity rules first.
Example
This example shows a pod spec with podAffinity that prefers to run on nodes where pods with label app: frontend exist.
apiVersion: v1
kind: Pod
metadata:
name: example-pod
labels:
app: backend
spec:
affinity:
podAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: app
operator: In
values:
- frontend
topologyKey: kubernetes.io/hostname
containers:
- name: backend-container
image: nginxWhen to Use
Use pod affinity when your pods benefit from being close to certain other pods. For example:
- Microservices that communicate frequently and need low latency.
- Pods sharing local storage or cache.
- Workloads that perform better when grouped on the same node or rack.
This helps improve performance and resource efficiency in your cluster.
Key Points
- Pod affinity schedules pods near other pods based on labels.
- It uses
preferredDuringSchedulingIgnoredDuringExecutionorrequiredDuringSchedulingIgnoredDuringExecutionrules. - Improves communication speed and resource sharing.
- Works by matching pod labels and node topology keys.
- Helps optimize cluster performance and pod placement.