Skip to main content

Containers and Kubernetes · Advanced · 25 min

Control where pods run with node affinity, taints and tolerations

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Kubernetes 1.37 · kind 0.33 · kubeconform 0.8.0

You will steer pods onto chosen nodes of a three-node Kubernetes 1.37 kind cluster with labels, node affinity and pod anti-affinity, reserve a node for batch work with a taint, watch a NoExecute taint evict pods on a timer, and see a high-priority pod preempt a low-priority one.

On this page

The Kubernetes scheduler places each new pod on a node in two passes. First it filters: any node that cannot run the pod is ruled out, because it lacks the free CPU or memory the pod requests, does not carry a label the pod demands, or has a taint the pod does not tolerate. Then it scores the nodes that are left and picks the best one. Almost everything in this tutorial is a way of adding your own rules to one of those two passes.

You will use three tools, and it helps to keep their directions straight. Labels with node affinity pull a pod towards nodes. Pod anti-affinity pushes a pod away from other pods. Taints push pods away from a node unless the pod carries a matching toleration. On top of these, priority decides who wins when there is not enough room for everyone.

You will build a kind cluster with one control-plane node and two workers, called placement, and keep every manifest in ~/placement-demo. All the workloads go in a placement-demo namespace, so clean-up at the end is short. Spreading replicas evenly across zones with topologySpreadConstraints is covered in part 6 of the Snip series, /tutorials/scale-snip-with-a-horizontal-pod-autoscaler, and is not repeated here.

Step 1 · Create a three-node cluster and install kubeconform

kubeconform checks manifests against the Kubernetes API schemas before they reach the cluster, so a typo such as tolerationSecond: fails on your laptop instead of in a confusing apply error. Install release 0.8.0:

Bash
ARCH="$(dpkg --print-architecture)"
curl -fsSL "https://github.com/yannh/kubeconform/releases/download/v0.8.0/kubeconform-linux-${ARCH}.tar.gz" -o /tmp/kubeconform.tar.gz
sudo tar -xzf /tmp/kubeconform.tar.gz -C /usr/local/bin kubeconform
rm /tmp/kubeconform.tar.gz
kubeconform -v
mkdir -p ~/placement-demo

On macOS, brew install kubeconform does the same. A binary installed by hand gets no apt updates; to upgrade, repeat the commands with the newer version from the project's releases page.

Scheduling rules need more than one node to mean anything. Write a kind config with a control plane and two workers, all on the Kubernetes 1.37 node image:

Bash
cat > ~/placement-demo/cluster.yaml <<'YAML'
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
  - role: control-plane
    image: kindest/node:v1.37.0
  - role: worker
    image: kindest/node:v1.37.0
  - role: worker
    image: kindest/node:v1.37.0
YAML
grep -c 'role: worker' ~/placement-demo/cluster.yaml

The grep prints 2. Create the cluster and the namespace:

Bash
kind create cluster --name placement --config ~/placement-demo/cluster.yaml --wait 120s
kubectl create namespace placement-demo
kubectl get nodes

kind names the nodes after the cluster: placement-control-plane, placement-worker and placement-worker2, and kind create cluster switches your kubectl context to kind-placement.

Check it worked

kubectl get nodes lists three nodes, all Ready. Now look at the one rule the cluster already has:

Bash
kubectl describe node placement-control-plane | grep -A2 Taints

It shows node-role.kubernetes.io/control-plane:NoSchedule. That taint is why your workloads never land on the control-plane node: from the scheduler's point of view this cluster has two places to put pods, not three. Keep that in mind for the later steps.

Step 2 · Label nodes and pin a pod with nodeSelector

A label is a key and value on a node, the same kind of label you put on pods. Every node already carries some, set by the kubelet, such as kubernetes.io/hostname and kubernetes.io/arch. Add your own to describe the hardware. Here placement-worker plays a node with fast disks and placement-worker2 a standard one:

Bash
kubectl label node placement-worker tier=fast
kubectl label node placement-worker2 tier=standard
kubectl get nodes -L tier

nodeSelector is the simplest placement rule: the pod only runs on nodes that carry every listed label with exactly that value.

Bash
cat > ~/placement-demo/fast-only.yaml <<'YAML'
apiVersion: v1
kind: Pod
metadata:
  name: fast-only
  namespace: placement-demo
spec:
  nodeSelector:
    tier: fast
  containers:
    - name: app
      image: busybox:1.37
      command: ["sleep", "3600"]
      resources:
        requests:
          cpu: 50m
          memory: 16Mi
---
apiVersion: v1
kind: Pod
metadata:
  name: needs-gpu
  namespace: placement-demo
spec:
  nodeSelector:
    tier: gpu
  containers:
    - name: app
      image: busybox:1.37
      command: ["sleep", "3600"]
      resources:
        requests:
          cpu: 50m
          memory: 16Mi
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/placement-demo/fast-only.yaml

No node is labelled tier=gpu, so the second pod has nowhere to go.

Bash
kubectl apply -f ~/placement-demo/fast-only.yaml
kubectl get pods -n placement-demo -o wide

Check it worked

The NODE column shows fast-only on placement-worker, and needs-gpu stays Pending with no node. Ask why:

Bash
kubectl describe pod needs-gpu -n placement-demo | tail -n 3

The FailedScheduling event says something like 0/3 nodes are available: 1 node(s) had untolerated taint {node-role.kubernetes.io/control-plane: }, 2 node(s) didn't match Pod's node affinity/selector. Learn to read that line: it tells you, node by node, which filter ruled each one out. It is the first thing to check whenever a pod is stuck in Pending. Delete both pods:

Bash
kubectl delete -f ~/placement-demo/fast-only.yaml

Step 3 · Use required and preferred node affinity

nodeSelector only does "label equals value, all of them". Node affinity does the same job with more expressive rules, in two strengths:

  • requiredDuringSchedulingIgnoredDuringExecution is a filter. A node that fails it is ruled out, exactly like a nodeSelector miss.
  • preferredDuringSchedulingIgnoredDuringExecution is a score. Each matching rule adds its weight (1 to 100) to a node's score, but a node that matches nothing can still be chosen.

Each rule is a list of matchExpressions with an operator: In, NotIn, Exists, DoesNotExist, and Gt or Lt for numeric values. Expressions inside one term must all match; if you list several nodeSelectorTerms, any one of them is enough.

This Deployment must run on a node that has any tier label, and would rather have tier=fast:

Bash
cat > ~/placement-demo/api.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
  namespace: placement-demo
spec:
  replicas: 4
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
              - matchExpressions:
                  - key: tier
                    operator: Exists
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 80
              preference:
                matchExpressions:
                  - key: tier
                    operator: In
                    values: ["fast"]
      containers:
        - name: api
          image: nginx:1.30-alpine
          resources:
            requests:
              cpu: 50m
              memory: 32Mi
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/placement-demo/api.yaml
Bash
kubectl apply -f ~/placement-demo/api.yaml
kubectl rollout status deployment/api -n placement-demo
kubectl get pods -n placement-demo -l app=api -o wide

Most or all of the four pods land on placement-worker. Do not be surprised if one goes to placement-worker2: the preference is one score among several the scheduler adds up, including how evenly the nodes are already loaded. When a rule must hold, make it required.

The IgnoredDuringExecution half of the name matters too. Remove the tier label from placement-worker, then look again:

Bash
kubectl label node placement-worker tier-
kubectl get pods -n placement-demo -l app=api -o wide

The trailing - removes a label. The running pods stay where they are, even though that node no longer meets the required rule: affinity is only checked when a pod is scheduled. Now restart the Deployment so new pods are scheduled:

Bash
kubectl rollout restart deployment/api -n placement-demo
kubectl rollout status deployment/api -n placement-demo
kubectl get pods -n placement-demo -l app=api -o wide

Check it worked

After the restart, all four api pods run on placement-worker2, the only node left with a tier label. Put the label back and delete the Deployment before the next step:

Bash
kubectl label node placement-worker tier=fast
kubectl delete -f ~/placement-demo/api.yaml

Step 4 · Keep replicas apart with pod anti-affinity

Two replicas on the same node are one node failure away from zero. Pod anti-affinity says "do not put me in the same place as pods that match this selector", where "place" is defined by topologyKey: a node label whose value groups nodes. With kubernetes.io/hostname, every node is its own group, so the rule means "one replica per node". With a zone label such as topology.kubernetes.io/zone on a cloud cluster, it means "one replica per zone".

Bash
cat > ~/placement-demo/web.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: placement-demo
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchLabels:
                  app: web
              topologyKey: kubernetes.io/hostname
      containers:
        - name: web
          image: nginx:1.30-alpine
          resources:
            requests:
              cpu: 50m
              memory: 32Mi
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/placement-demo/web.yaml

The labelSelector matches the Deployment's own pods, so each replica avoids its siblings. Apply it, then ask for one more replica than there are schedulable nodes:

Bash
kubectl apply -f ~/placement-demo/web.yaml
kubectl rollout status deployment/web -n placement-demo
kubectl scale deployment/web -n placement-demo --replicas=3
kubectl get pods -n placement-demo -l app=web -o wide

Check it worked

The first two pods run on different workers, one each. The third stays Pending, and kubectl describe on it shows a FailedScheduling event mentioning that nodes didn't match the pod anti-affinity rules. This is the trade-off of a required rule: it would rather leave a replica unscheduled than break the rule.

If you would rather run all replicas and only spread them when you can, use preferredDuringSchedulingIgnoredDuringExecution with a weight and a podAffinityTerm. For an even spread across many nodes or zones, rather than "never two together", topologySpreadConstraints is the better tool; part 6 of the Snip series shows it. Inter-pod rules are also slower to evaluate than node rules, and the Kubernetes docs advise against them on clusters of several hundred nodes or more. Delete the Deployment:

Bash
kubectl delete -f ~/placement-demo/web.yaml

Step 5 · Dedicate a node to batch work with a taint

A taint is set on a node and has three parts, key=value:effect. The effect says what happens to pods that do not tolerate it:

  • NoSchedule: new pods are not scheduled there. Pods already running stay.
  • PreferNoSchedule: the scheduler tries to avoid the node, but uses it if there is nowhere else.
  • NoExecute: new pods are not scheduled, and running pods are evicted. The next step covers it.

Reserve placement-worker2 for batch jobs. A dedicated node is common when one kind of work would starve the rest: a nightly report export on a small, budget-limited cluster, for example, should not slow the API that customers on mobile data are waiting on.

Bash
kubectl taint node placement-worker2 dedicated=batch:NoSchedule
kubectl label node placement-worker2 dedicated=batch

You need both commands. The taint keeps other pods off the node. But a toleration only allows a pod onto a tainted node; it does not draw the pod there, so a batch pod with only a toleration could still land on placement-worker. The label gives batch pods something to select.

Bash
cat > ~/placement-demo/batch.yaml <<'YAML'
apiVersion: v1
kind: Pod
metadata:
  name: nightly-report
  namespace: placement-demo
spec:
  nodeSelector:
    dedicated: batch
  tolerations:
    - key: dedicated
      operator: Equal
      value: batch
      effect: NoSchedule
  containers:
    - name: report
      image: busybox:1.37
      command: ["sleep", "3600"]
      resources:
        requests:
          cpu: 50m
          memory: 16Mi
---
apiVersion: v1
kind: Pod
metadata:
  name: wants-batch-node
  namespace: placement-demo
spec:
  nodeSelector:
    dedicated: batch
  containers:
    - name: app
      image: busybox:1.37
      command: ["sleep", "3600"]
      resources:
        requests:
          cpu: 50m
          memory: 16Mi
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/placement-demo/batch.yaml

operator: Equal matches key, value and effect exactly. operator: Exists with only a key matches any value of that key; a toleration with operator: Exists and no key at all tolerates every taint, which is what node agents such as kube-proxy use.

Bash
kubectl apply -f ~/placement-demo/batch.yaml
kubectl get pods -n placement-demo -o wide

Check it worked

nightly-report runs on placement-worker2. wants-batch-node selects the batch node but has no toleration, so it stays Pending, and its event mentions the untolerated taint {dedicated: batch}. Every ordinary pod you create from now on goes to placement-worker. Delete the two pods but keep the taint and label; the preemption step works around them:

Bash
kubectl delete -f ~/placement-demo/batch.yaml

Step 6 · Evict pods on a timer with NoExecute

NoExecute acts on pods that are already running. A pod without a matching toleration is evicted at once. A pod whose toleration sets tolerationSeconds may stay that many seconds after the taint appears, then is evicted. A pod that tolerates the taint with no tolerationSeconds stays indefinitely.

Kubernetes uses this itself. When a node stops reporting, the control plane taints it node.kubernetes.io/unreachable:NoExecute (or not-ready), and every pod gets a toleration for those taints with tolerationSeconds: 300 added automatically unless it sets its own. That is why pods on a dead node take about five minutes to be replaced.

Write three pods pinned to placement-worker through its hostname label:

Bash
cat > ~/placement-demo/noexecute.yaml <<'YAML'
apiVersion: v1
kind: Pod
metadata:
  name: leaves-now
  namespace: placement-demo
spec:
  nodeSelector:
    kubernetes.io/hostname: placement-worker
  containers:
    - name: app
      image: busybox:1.37
      command: ["sleep", "3600"]
---
apiVersion: v1
kind: Pod
metadata:
  name: leaves-after-60s
  namespace: placement-demo
spec:
  nodeSelector:
    kubernetes.io/hostname: placement-worker
  tolerations:
    - key: maintenance
      operator: Exists
      effect: NoExecute
      tolerationSeconds: 60
  containers:
    - name: app
      image: busybox:1.37
      command: ["sleep", "3600"]
---
apiVersion: v1
kind: Pod
metadata:
  name: stays
  namespace: placement-demo
spec:
  nodeSelector:
    kubernetes.io/hostname: placement-worker
  tolerations:
    - key: maintenance
      operator: Exists
      effect: NoExecute
  containers:
    - name: app
      image: busybox:1.37
      command: ["sleep", "3600"]
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/placement-demo/noexecute.yaml
Bash
kubectl apply -f ~/placement-demo/noexecute.yaml
kubectl wait --for=condition=Ready pod --all -n placement-demo --timeout=90s
kubectl get pod leaves-now -n placement-demo -o jsonpath='{.spec.tolerations}{"\n"}'

The last command shows the two automatic tolerations, for not-ready and unreachable, each with tolerationSeconds of 300, even though the manifest has none.

Before the next command: a NoExecute taint evicts every pod on the node that does not tolerate it, not only your demo pods. System pods such as CoreDNS may be evicted too and restart on another node. On a shared cluster, take a node out of service with kubectl drain instead, which respects PodDisruptionBudgets. In a second terminal, start a watch, then taint the node:

Bash
kubectl get pods -n placement-demo -o wide --watch
Bash
kubectl taint node placement-worker maintenance=true:NoExecute

Check it worked

In the watch, leaves-now goes to Terminating within seconds. leaves-after-60s keeps running for about a minute, then terminates. stays keeps running. The evicted pods are gone for good, because nothing owns them; pods from a Deployment would be recreated on another node that accepts them. Press Ctrl+C, then remove the taint (the trailing - again) and delete the remaining pod:

Bash
kubectl taint node placement-worker maintenance=true:NoExecute-
kubectl delete -f ~/placement-demo/noexecute.yaml --ignore-not-found

Step 7 · Let important pods preempt others with PriorityClasses

So far, a pod that does not fit waits. Priority changes that. A PriorityClass is a cluster-wide object with a number; a pod names one in priorityClassName. When a pod cannot be scheduled, the scheduler looks for a node where evicting lower-priority pods would make room, evicts them, and places the pod there. This is preemption.

To see it you need a node that is full. kind nodes share your machine's CPUs, so read how much CPU placement-worker can allocate and size a request at 60% of it. One such pod fits; two do not:

Bash
ALLOC="$(kubectl get node placement-worker -o jsonpath='{.status.allocatable.cpu}')"
case "$ALLOC" in
  *m) MILLI="${ALLOC%m}" ;;
  *) MILLI="$((ALLOC * 1000))" ;;
esac
SLOT="$((MILLI * 6 / 10))m"
echo "$SLOT"

On a machine with 8 CPUs this prints 4800m. The variable only lives in this terminal, so write the manifests in the same one:

Bash
: "${SLOT:?Run the SLOT commands above first}"
cat > ~/placement-demo/priority-classes.yaml <<'YAML'
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
  name: placement-low
value: 1000
globalDefault: false
description: "Work that can wait, such as reports."
---
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
  name: placement-high
value: 100000
globalDefault: false
preemptionPolicy: PreemptLowerPriority
description: "Customer-facing services."
YAML
cat > ~/placement-demo/preemption.yaml <<YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: report
  namespace: placement-demo
  labels:
    app: report
spec:
  replicas: 1
  selector:
    matchLabels:
      app: report
  template:
    metadata:
      labels:
        app: report
    spec:
      priorityClassName: placement-low
      nodeSelector:
        kubernetes.io/hostname: placement-worker
      containers:
        - name: report
          image: busybox:1.37
          command: ["sleep", "3600"]
          resources:
            requests:
              cpu: ${SLOT}
              memory: 16Mi
---
apiVersion: v1
kind: Pod
metadata:
  name: checkout
  namespace: placement-demo
spec:
  priorityClassName: placement-high
  nodeSelector:
    kubernetes.io/hostname: placement-worker
  containers:
    - name: checkout
      image: busybox:1.37
      command: ["sleep", "3600"]
      resources:
        requests:
          cpu: ${SLOT}
          memory: 16Mi
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/placement-demo/priority-classes.yaml ~/placement-demo/preemption.yaml

The second heredoc has no quotes around YAML, so the shell fills in ${SLOT}. Both workloads are pinned to placement-worker so the only way to fit checkout is to remove report; placement-worker2 is still reserved for batch work anyway. A few rules for real classes:

  • Values up to one billion are yours to use. Higher values are reserved for the built-in system-cluster-critical and system-node-critical classes, which protect components such as CoreDNS.
  • Set globalDefault: true on at most one class to give it to every pod without a priorityClassName. Without one, such pods have priority 0.
  • preemptionPolicy: Never gives a pod a place at the front of the scheduling queue without letting it evict anyone, which suits urgent batch jobs.

Apply the classes and the low-priority Deployment first, then the high-priority pod:

Bash
kubectl apply -f ~/placement-demo/priority-classes.yaml
kubectl apply -f ~/placement-demo/preemption.yaml --selector app=report
kubectl rollout status deployment/report -n placement-demo
kubectl apply -f ~/placement-demo/preemption.yaml
kubectl get pods -n placement-demo -o wide --watch

The --selector on the second command applies only the objects labelled app=report, which here is the Deployment.

Check it worked

The watch shows the report pod terminating, checkout starting on placement-worker, and a new report pod in Pending, because its only allowed node is now full. Press Ctrl+C and look for the scheduler's record of it:

Bash
kubectl get events -n placement-demo --field-selector reason=Preempted

It shows something like Preempted by pod ... on node placement-worker. Preemption ends the victim gracefully, using its termination grace period, and the scheduler tries to respect PodDisruptionBudgets but does not guarantee it. Give low-priority workloads a budget and a sensible grace period if being preempted halfway through matters to them.

Step 8 · Clean up the cluster changes

Delete the namespace and everything in it, then the two PriorityClasses, which are cluster-scoped and so are not in the namespace:

Bash
kubectl delete namespace placement-demo
kubectl delete -f ~/placement-demo/priority-classes.yaml

If you keep the cluster, remove the labels and taint you added so the nodes are plain again:

Bash
kubectl label node placement-worker tier-
kubectl label node placement-worker2 tier- dedicated-
kubectl taint node placement-worker2 dedicated=batch:NoSchedule-

Or delete the whole cluster, which removes all of the above at once:

Bash
kind delete cluster --name placement

Finally remove the demo folder:

Bash
rm -r ~/placement-demo

Check it worked

kubectl get priorityclass lists only the built-in system- classes, and kubectl get nodes -L tier,dedicated shows empty columns, or kind get clusters no longer lists placement if you deleted the cluster. ~/placement-demo is gone.

Next steps

  • Go back over creating and deleting kind clusters and switching contexts: /tutorials/run-your-first-kubernetes-cluster-with-kind.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.