Kubernetes affinity anti-affinity rules are how you tell the scheduler where your pods should and should not run, beyond the simple label selector of nodeSelector. They let you express ideas like “run this workload only on nodes with fast disks”, “keep this cache next to the application that uses it”, and “never put two replicas of this service on the same node”. Without these rules, the scheduler spreads pods on a best-effort basis, which is fine for stateless workloads but dangerous for anything with availability requirements, because two replicas can quietly land on the same node and disappear together when that node fails. This guide explains node affinity, pod affinity, and pod anti-affinity with complete YAML examples, shows how to verify the result, and covers the failures you will actually see in practice.
Before diving into syntax, it helps to understand the two flavours of every affinity rule: required and preferred. Required rules are hard constraints: if no node satisfies them, the pod stays Pending and the scheduler will not place it anywhere else. Preferred rules are soft preferences with a weight from 1 to 100: the scheduler tries to honour them, but it will place the pod somewhere else rather than leave it unscheduled. That distinction is the most important design decision in this whole topic. A required rule that is too strict causes an outage of a different kind, where pods cannot schedule at all, while a preferred rule that is too weak may be ignored exactly when you needed it. The art of affinity is choosing hard rules only for genuine requirements and soft rules for everything else. If you are still building your scheduling fundamentals, our guide to Kubernetes resource requests and limits pairs naturally with this one, because requests determine which nodes are even eligible before affinity is considered.

Prerequisites
You need access to a Kubernetes cluster with kubectl configured, and permission to create deployments in a namespace you control. A local cluster such as kind or minikube works for learning, but the availability lessons only become visible with at least two worker nodes, so a two or three node cluster is much better for experimenting with anti-affinity. You should be comfortable applying manifests with kubectl apply, inspecting pods with kubectl get pods, and reading scheduler events with kubectl describe pod. The examples use the standard well-known labels kubernetes.io/hostname and topology.kubernetes.io/zone, which are present on nodes in virtually every managed and self-hosted cluster. No additional controllers or operators are required: affinity is a core scheduler feature available in every Kubernetes version you are likely to run.
Kubernetes Affinity Anti-Affinity: Node Affinity Basics
Node affinity constrains which nodes are eligible for a pod based on node labels. It replaces nodeSelector with a much more expressive syntax, including match expressions with operators such as In, NotIn, Exists, DoesNotExist, Gt, and Lt. A required node affinity rule says the pod may only run on nodes whose labels match, while a preferred rule says the scheduler should favour those nodes with a given weight. The example below requires SSD-backed nodes for a database workload and prefers nodes in a particular zone when several SSD nodes are available.
apiVersion: apps/v1
kind: Deployment
metadata:
name: db
spec:
replicas: 1
selector:
matchLabels:
app: db
template:
metadata:
labels:
app: db
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: disktype
operator: In
values:
- ssd
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 80
preference:
matchExpressions:
- key: topology.kubernetes.io/zone
operator: In
values:
- us-east-1a
The long field name requiredDuringSchedulingIgnoredDuringExecution deserves a plain explanation. The “required during scheduling” part means the rule is enforced when the pod is placed. The “ignored during execution” part means that if node labels change after the pod is running, the scheduler will not evict the pod; it keeps running where it is until something else reschedules it. This is usually what you want, because evicting a running workload just because a label changed would be surprising and disruptive. If you need labels to be enforced continuously, that is a job for taints and tolerations or for a descheduler, not for affinity.
Pod Affinity: Keeping Related Pods Together
Pod affinity attracts pods to nodes that already run pods matching a selector. The classic use case is a cache or a sidecar-like helper that should run on the same node as the application it serves, so that traffic between them stays local and fast. The rule below says that cache pods prefer nodes already running pods labelled app=web, using the hostname topology so that “together” means the same node rather than merely the same zone. Note that pod affinity is expressed from the perspective of the pod being scheduled: the cache pod carries the rule that pulls it toward web pods.
affinity:
podAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchLabels:
app: web
topologyKey: kubernetes.io/hostname
The topologyKey is the part people get wrong most often, so it is worth dwelling on. The topologyKey defines the granularity of “together” or “apart”: kubernetes.io/hostname means the same or a different node, while topology.kubernetes.io/zone means the same or a different availability zone. Choosing the zone key when you meant the hostname key produces a rule that is satisfied far too easily, because pods in the same zone but on different nodes still count as co-located. Conversely, choosing the hostname key when you wanted zone spreading can make a rule unsatisfiable on a small cluster. Always read the topologyKey as the answer to the question “together or apart at what level”, and pick the level that matches your actual failure domain.
Kubernetes Affinity Anti-Affinity: Pod Anti-Affinity for Availability
Pod anti-affinity is the mirror image: it repels pods from nodes that already run matching pods. This is the rule that turns a three-replica deployment into a genuinely highly available service instead of three pods that happen to share one node. The example below is the single most useful anti-affinity pattern in production Kubernetes: a required rule that forbids two pods of the same application from sharing a hostname, combined with a preferred rule that also spreads them across zones when the scheduler has a choice.
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: web
topologyKey: kubernetes.io/hostname
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchLabels:
app: web
topologyKey: topology.kubernetes.io/zone
Think carefully before making the hostname rule required. On a cluster with fewer nodes than replicas, a required anti-affinity rule makes the extra replicas unschedulable, and they will sit in Pending forever. That is correct behaviour for a strict availability requirement, but it is a bad surprise if you scale up during an incident and discover that the new replicas cannot schedule because there are not enough nodes. A common compromise is to make hostname spreading preferred with a high weight and zone spreading preferred with a lower weight, so the scheduler spreads aggressively when it can but still schedules when it cannot. The right choice depends on whether an unscheduled replica or a co-located replica is worse for your service, and that is a decision worth making deliberately rather than by copying an example. Health checking matters here too: spreading is only useful if unhealthy pods are detected and replaced, which is why our guide to Kubernetes liveness and readiness probes belongs in the same conversation.
Weights, Operators, and Match Expressions
Weights on preferred rules range from 1 to 100, and the scheduler adds up the weights of all matching preferred terms for each node, then favours the highest scoring nodes. A weight of 100 does not mean “almost required”; it simply outranks lower weights when the scheduler compares candidates. If two preferred rules conflict, the higher total wins, and ties are broken by the scheduler’s other scoring plugins, including resource fitting and image locality. Use weights to express genuine priorities: give your most important preference a high weight and lesser preferences lower weights, rather than setting everything to 100 and hoping the scheduler reads your mind.
Match expressions give you operators beyond simple equality. In matches a value in a list, NotIn excludes values, Exists matches any node carrying the label regardless of value, and Gt and Lt compare integer label values, which is useful for labels like a generation number or a capacity tier. A required rule can combine several match expressions in one term, and all expressions in a term must match, while a list of several terms means any term may match. That AND within a term and OR across terms structure is easy to misread, so when a rule behaves unexpectedly, re-read it with that logic in mind before assuming the scheduler is broken. The official documentation on assigning pods to nodes documents every operator and field precisely.
Applying and Verifying the Scheduling Result
Apply the manifest and verify where the pods landed. The -o wide output adds the node column, which is the fastest way to confirm that anti-affinity actually spread your replicas. Do not trust the manifest alone: apply it, look at the nodes, and then scale the deployment up and down to see how the scheduler behaves under change.
kubectl apply -f web-deployment.yaml
kubectl get pods -o wide -l app=web
kubectl describe pod web-abc123 | grep -A 10 Events
For a three-replica deployment with hostname anti-affinity on a three-node cluster, you should see one pod per node. If you see two pods on one node, either the rule is preferred rather than required and the scheduler had a reason to co-locate them, or the pods were created before the rule existed and have not been rescheduled. Remember that affinity is only evaluated at scheduling time: editing a deployment to add a rule does not move existing pods, because the rollout creates new pods that are scheduled with the new rule while old pods terminate. A rolling update is therefore the mechanism that applies a new affinity rule to a running workload.
Troubleshooting
Pending pods are the signature symptom of an unsatisfiable required rule. Run kubectl describe pod on the pending pod and read the Events section: the scheduler records messages such as “did not match pod anti-affinity rules” or “did not match node selector”, which tell you exactly which rule failed and on how many nodes. Count your nodes against your replicas and check the labels on each node with kubectl get nodes –show-labels. If the rule requires a label that no node carries, either fix the label or relax the rule; if the rule requires more distinct nodes than exist, either add nodes or make the rule preferred.
A second common failure is affinity that seems to have no effect. The usual causes are a label selector that matches nothing, a topologyKey that is too coarse, or pods that were scheduled before the rule was added and never rescheduled. Check the selector against the actual pod labels with kubectl get pods –show-labels, confirm the topologyKey matches your intent, and force a rollout with kubectl rollout restart if the pods predate the rule. Also remember that node affinity and pod affinity interact with taints, tolerations, and resource requests: a pod can satisfy every affinity rule and still stay Pending because no node has enough free CPU or memory, or because every eligible node is tainted. When the events mention multiple failed predicates, work through them one at a time rather than assuming affinity is the culprit.
Conclusion
Affinity and anti-affinity turn the Kubernetes scheduler from a best-effort placer into a tool that understands your availability and locality requirements. Use node affinity for hardware and zone constraints, pod affinity to keep cooperating workloads together, and pod anti-affinity to spread replicas across failure domains. Keep required rules for genuine requirements, express preferences with honest weights, choose topology keys that match your real failure domains, and always verify with kubectl get pods -o wide rather than assuming the manifest did what you intended. Scheduled thoughtfully, these rules are the difference between a deployment that survives a node failure and one that merely looks redundant.