Advanced example
Pod Anti-Affinity (Spread)
Spread replicas across nodes for high availability.
For high availability, spread replicas across nodes so a single node failure doesn't take down all replicas. Use podAntiAffinity. Note: spreading increases cross-node traffic and egress.
Soft anti-affinity (preferred)
# Each replica prefers a different node (soft: preferredDuringScheduling)
apiVersion: apps/v1
kind: Deployment
metadata:
name: ha-app
spec:
replicas: 3
selector:
matchLabels:
app: ha-app
template:
metadata:
labels:
app: ha-app
spec:
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchLabels:
app: ha-app
topologyKey: kubernetes.io/hostname
containers:
- name: app
image: nginx:alpine
resources:
requests:
cpu: "100m"
memory: "128Mi"
The scheduler tries to spread replicas but will place multiple on the same node if needed.
Hard anti-affinity (required)
Use requiredDuringSchedulingIgnoredDuringExecution for hard spread — replicas will stay Pending if there aren't enough nodes.
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: ha-app
topologyKey: kubernetes.io/hostname