Kubernetes spread pods evenly accross nodes

Suppose we have 3 node cluster and deploying simple deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: demo
  labels:
    app: demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: demo
  template:
    metadata:
      labels:
        app: demo
    spec:
      containers:
        - name: nginx
          image: nginx:alpine

And after that scaling it:

kubectl scale deployment demo --replicas=10

And check what happens:

kubectl get po -l app=demo -o wide

Depending on a situation we can have all ten pods on single node

From one side kubernetes does not really care, from another it sees that ony of nodes already have image downloaded and there is also bazillion of other conditions

Here is example of deployment with topologySpreadConstraints which will ask Kubernetes to spread pods accross all nodes

apiVersion: apps/v1
kind: Deployment
metadata:
  name: demo
  labels:
    app: demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: demo
  template:
    metadata:
      labels:
        app: demo
    spec:
      # ask Kubernetes to spread pods across nodes
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: ScheduleAnyway
          labelSelector:
            matchLabels:
              app: demo

      containers:
        - name: nginx
          image: nginx:alpine

Note: that still if two of three nodes are full, then Kubernetes will have no other options rather than creating all ten pods on a third one