Kubernetes Pod Scheduling: Topology Spread Constraints
topologySpreadConstraints gives you fine-grained control over how pods distribute across failure domains. Unlike pod anti-affinity which enforces at most one pod per domain, maxSkew sets the maximum allowed difference in pod count between any two domains.
Topology Spread Constraints - Kubernetes Docs
The cluster is pre-configured with zone labels - cplane-01 and node-01 are in zone-a, node-02 is in zone-b. Run kubectl get nodes --show-labels to confirm before starting.
Task 1 - Node-Level Spread
With topologyKey: kubernetes.io/hostname, each node is a separate domain. The scheduler counts pods per node and enforces that no node has more than maxSkew extra pods compared to any other. With 4 replicas across 3 nodes and maxSkew: 1, the result is a 2-1-1 distribution.
Steps:
- Create a Deployment named
web, imagenginx:alpine, 4 replicas, labelapp: web - Add
topologySpreadConstraintswithmaxSkew: 1,topologyKey: kubernetes.io/hostname,whenUnsatisfiable: DoNotSchedule, and alabelSelectormatchingapp: web
Hint: Where topologySpreadConstraints goes
Add topologySpreadConstraints under spec.template.spec. Each entry needs maxSkew, topologyKey, whenUnsatisfiable, and labelSelector.matchLabels pointing to the pod's own labels so the scheduler counts existing pods in each domain.
Task 2 - Zone-Level Spread
Changing topologyKey to topology.kubernetes.io/zone shifts the distribution unit from node to zone. The scheduler counts pods per zone instead of per node - within a zone, multiple pods may land on the same node. With 4 replicas across 2 zones and maxSkew: 1, the result is a 2-2 split.
Steps:
- Create a Deployment named
zone-web, imagenginx:alpine, 4 replicas, labelapp: zone-web - Add
topologySpreadConstraintswithmaxSkew: 1,topologyKey: topology.kubernetes.io/zone,whenUnsatisfiable: DoNotSchedule, and alabelSelectormatchingapp: zone-web
This challenge is part of the Kubernetes Pod Scheduling skill path.