nodeSelector

nodeSelector constrains a Pod to run only on nodes carrying specific labels.

Syntaxspec: nodeSelector: <label-key>: <label-value>

By default the scheduler is free to place a Pod on any node. Sometimes you need control — a GPU workload belongs on GPU nodes, a data job near fast disks. The simplest tool is nodeSelector.

How it works

  1. Label the nodes, e.g. disktype=ssd.
  2. Add a matching nodeSelector to the Pod spec.

The scheduler will only place the Pod on nodes whose labels match all the given pairs. If none match, the Pod stays Pending.

Example

Example · yaml
# First label a node:
# kubectl label node worker-1 disktype=ssd

apiVersion: v1
kind: Pod
metadata:
  name: ssd-pod
spec:
  nodeSelector:
    disktype: ssd
  containers:
    - name: app
      image: myapp:1.0

When to use it

  • A team labels GPU nodes with accelerator=nvidia and adds a nodeSelector to ML training pods so they are scheduled only on those nodes.
  • A multi-region cluster uses nodeSelector with topology.kubernetes.io/region=us-east-1 to pin latency-sensitive pods to nodes in a specific region.
  • A security-sensitive workload uses nodeSelector to run only on nodes labelled compliance=pci so it is isolated from general workloads.

More examples

Label a node and use nodeSelector

Labels a node with a custom key-value pair that pods can then reference in their nodeSelector to target this node.

Example · bash
kubectl label node worker-2 accelerator=nvidia
kubectl get node worker-2 --show-labels | grep accelerator

Pod with nodeSelector

Constrains the GPU training pod to nodes labelled accelerator=nvidia and requests one GPU device resource.

Example · yaml
apiVersion: v1
kind: Pod
metadata:
  name: gpu-training
spec:
  nodeSelector:
    accelerator: nvidia
  containers:
    - name: train
      image: pytorch/pytorch:2.1-cuda11.8
      resources:
        limits:
          nvidia.com/gpu: 1

Verify pod placement

Confirms that the pod landed on the node with the matching label by checking the NODE column and describe output.

Example · bash
kubectl get pod gpu-training -o wide
# NAME          READY  STATUS   NODE
# gpu-training  1/1    Running  worker-2

kubectl describe pod gpu-training | grep Node:

Discussion

  • Be the first to comment on this lesson.