Back to Practice
Lab

Co-locate and Spread Pods with Affinity

Steer co-scheduling with inter-pod affinity: co-locate a web Pod with its cache using required pod affinity, then spread web replicas with preferred pod anti-affinity — and learn why required rules go Pending when there aren't enough nodes.

Your mission

nodeSelector and node affinity answer "which node should this Pod run on?" Inter-pod affinity answers a different question: "which other Pods should this one run near — or far from?" You express placement relative to where other Pods already are, not relative to node labels.

Two directions:

  • Pod affinity pulls a Pod toward others. Classic use: keep a web Pod on the same node as its cache so the hop between them never leaves the box.
  • Pod anti-affinity pushes a Pod away from others. Classic use: spread the replicas of a service across nodes so one node failing doesn't take them all.

Both come in two strengths, and the difference is the whole ballgame:

  • requiredDuringSchedulingIgnoredDuringExecution — a hard rule. If it can't be satisfied, the Pod stays Pending.
  • preferredDuringSchedulingIgnoredDuringExecution — a soft rule with a weight. The scheduler tries to honor it but will place the Pod anyway if it can't.

Every affinity term needs a topologyKey — the node label that defines "same place." kubernetes.io/hostname means "the same node."

Your lab cluster has one schedulable node. That makes required anti-affinity a trap: ask for two replicas that must not share a node, and the second has nowhere to go. You'll feel that directly in Task 02.

Useful aliases

In your terminal, k is aliased to kubectl and completion is configured. The jumpbox also has k9s, jq and yq installed.

Skills you'll put into practice

schedulingaffinitycka

Make it your own.

Use this topic as a starting point for a fresh custom scenario.

Create a variation