Script Valley
Kubernetes: From Containers to Clusters
Scaling, Scheduling, and Resource ManagementLesson 5.2

Kubernetes node selectors and node affinity: placing pods on specific nodes

nodeSelector field, node labels, node affinity types, requiredDuringSchedulingIgnoredDuringExecution, preferredDuringSchedulingIgnoredDuringExecution, operator types, affinity vs nodeSelector comparison, inter-pod affinity introduction

Control Where Pods Land

Kubernetes node affinity scheduling diagram

By default, the scheduler places Pods on any available node. nodeSelector and nodeAffinity let you constrain placement — run GPU workloads on GPU nodes, keep certain apps in specific availability zones, co-locate related services.

nodeSelector (Simple)

# Label a node
kubectl label node worker-1 disktype=ssd

# Require that label in the Pod spec
spec:
  nodeSelector:
    disktype: ssd

nodeAffinity (Flexible)

spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: zone
            operator: In
            values: ["us-east-1a", "us-east-1b"]
      preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 80
        preference:
          matchExpressions:
          - key: disktype
            operator: In
            values: ["ssd"]

required — Pod stays Pending if no matching node exists. preferred — try to match, but schedule anyway if no match. Use preferred for soft constraints to avoid Pods getting stuck.

Up next

Kubernetes taints and tolerations: reserving nodes for specific workloads

Sign in to track progress