0
0
KubernetesConceptBeginner · 3 min read

Pod Anti-Affinity in Kubernetes: What It Is and How It Works

In Kubernetes, 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.

yaml
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.3
Output
Pod will not be scheduled on a node that already has a pod with label app=frontend.
🎯

When 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 requiredDuringSchedulingIgnoredDuringExecution or preferredDuringSchedulingIgnoredDuringExecution rules.
  • topologyKey defines the node attribute to consider, commonly kubernetes.io/hostname.

Key Takeaways

Pod anti-affinity helps spread pods across nodes to avoid single points of failure.
It uses label selectors and topology keys to control pod placement.
Use it to increase availability by preventing pods from co-locating on the same node.
It supports required and preferred rules for flexible scheduling.
Commonly used in production to improve app resilience.