Advanced example
Pod Affinity (Co-locate)
Co-locate related pods on the same node to avoid egress fees.
Traffic between pods on different burst nodes can incur cloud egress charges. Use podAffinity to co-locate related pods (e.g. app + cache) on the same node. Use topologyKey: kubernetes.io/hostname so they land on the same host.
Soft affinity (preferred)
# Worker pods prefer to run on the same node as the app (reduces egress)
apiVersion: apps/v1
kind: Deployment
metadata:
name: worker
spec:
replicas: 2
selector:
matchLabels:
app: worker
template:
metadata:
labels:
app: worker
spec:
affinity:
podAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchLabels:
app: my-app
topologyKey: kubernetes.io/hostname
containers:
- name: worker
image: busybox:1.36
command: ["sleep", "infinity"]
resources:
requests:
cpu: "500m"
memory: "512Mi"
The scheduler tries to co-locate but will place elsewhere if needed.
Hard affinity (required)
Use requiredDuringSchedulingIgnoredDuringExecution when co-location is mandatory. The pod will stay Pending until a node has a matching pod.
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: my-app
topologyKey: kubernetes.io/hostname