K8s: Spread Pods Evenly on Nodes in Different Zones/Regions

Kubernetes automatically spreads Pods for workload resources (such as Deployment, StatefulSet, etc.) across different Nodes to reduce the impact of failures.

In a multi-zone (multi-region) Kubernetes cluster it is required to ensure that Kubernetes will place the replicas of a Pod on the Nodes in different zones, to reduce the impact of zone failures.

In this note I will show how to distribute Kubernetes Pod replicas evenly on Nodes in different zones using topologySpreadConstraints.

Spread Kubernetes Pods Evenly on Different Nodes

Label your Kubernetes Nodes with meta tags indicating the zones, where these Nodes are located, for example:

$ kubectl label node node1 node2 topology.kubernetes.io/zone=emea-east1
$ kubectl label node node3 node4 topology.kubernetes.io/zone=emea-west1

topologySpreadConstraints is a built-in Kubernetes feature that is used to distribute workloads across availability zones to ensure that Pods keep running even in case of an outage in one of the zones.

To spread Pod replicas evenly on the Nodes in different zones, in the Pod template define .spec.topologySpreadConstraints, as follows:

spec:
  topologySpreadConstraints:
    - maxSkew: 1
      topologyKey: topology.kubernetes.io/zone
      whenUnsatisfiable: DoNotSchedule
Parameter Description
maxSkew The maximum difference in the number of Pods that exist in different zone.
topologyKey A label key that Nodes need to share to define a Topology.
whenUnsatisfiable How to deal with a Pod if it doesn’t satisfy the spread constraint.

To get more detailed information and to see all the available parameters, read the official documentation.

Was it useful? Share this post with the world!

Leave a Reply