Pod Anti-Affinity in Kubernetes: What It Is and How It Works
pod anti-affinity is a rule that tells the scheduler to avoid placing certain pods on the same node or close nodes as other specified pods. It helps spread pods across nodes to improve availability and reduce risk of failure.How It Works
Pod anti-affinity works like a seating rule at a party where you want to keep certain guests apart to avoid crowding or conflicts. In Kubernetes, it tells the scheduler not to put pods with specific labels together on the same node or nearby nodes.
This spreading helps ensure that if one node fails, not all copies of your app go down at once. The scheduler checks the anti-affinity rules before placing a pod and skips nodes that violate these rules.
Example
This example shows a pod spec with podAntiAffinity that avoids placing pods with label app: frontend on the same node.
apiVersion: v1
kind: Pod
metadata:
name: example-pod
labels:
app: frontend
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- frontend
topologyKey: "kubernetes.io/hostname"
containers:
- name: nginx
image: nginx:1.23.3When to Use
Use pod anti-affinity when you want to improve your app's reliability by spreading pods across different nodes. This is useful for high availability setups where you don't want all replicas of a service to fail together.
For example, if you run multiple instances of a web server, anti-affinity ensures they run on separate nodes. This way, if one node crashes, others keep serving traffic.
Key Points
- Pod anti-affinity prevents pods with matching labels from being scheduled on the same or nearby nodes.
- It improves fault tolerance by spreading pods across nodes.
- It uses
requiredDuringSchedulingIgnoredDuringExecutionorpreferredDuringSchedulingIgnoredDuringExecutionrules. topologyKeydefines the node attribute to consider, commonlykubernetes.io/hostname.