Restrict Placement with nodeSelector and Node Affinity · Kubernetes
Put constraints in the Deployment Pod template to restrict eligible nodes.
Learn with progress and quizzesFirst, understand the concepts.
nodeSelector requires every match
Node labels must match every nodeSelector entry. In a Deployment, use spec.template.spec.nodeSelector. Labels on Deployment metadata do not select nodes.
Required versus preferred
Required affinity is mandatory; preferred affinity expresses a preference. If nodeSelector and required affinity are both present, both must be satisfied.
AND, OR, and later changes
Expressions within one term combine with AND, while multiple terms are alternatives. IgnoredDuringExecution does not evict existing Pods after label changes. Direct nodeName assignment bypasses scheduler selection and is different from ordinary placement constraints.
Why it matters
Hardware or licensing requirements may demand a mandatory node constraint rather than a preference. Remaining Pending when no node qualifies can be the intended result.
Work through the reasoning
Check the template location
Deployment metadata differs from the Pod template. Put nodeSelector and affinity under template.spec and inspect the resulting Pod. Read actual label values instead of assuming they equal node names.
Inspect the replacement
An impossible label leaves the new revision Pending, while an older Ready Pod may remain. One Running Pod does not prove the new configuration succeeded. Compare owner ReplicaSets and nodeName.
Learn by doing.
Use kubectl, a personal practice Kubernetes cluster, and a POSIX shell. cert-manager and VPA labs require the components specified in each lesson. Node-changing labs require a dedicated disposable worker. Use the practice namespaces.
Use at least one Ready, schedulable practice worker. Set export STUDY_NODE=actual-worker-name from the displayed list before running. The lab reads its existing hostname label without modifying Node labels. No node should match study.greatjin.net/missing-pool=unavailable in this practice cluster.
(
set -eu
kubectl config current-context
kubectl get nodes -L kubernetes.io/hostname
: "${STUDY_NODE:?Set STUDY_NODE to a Ready schedulable practice worker name}"
study_host=$(kubectl get node "$STUDY_NODE" -o jsonpath='{.metadata.labels.kubernetes\.io/hostname}')
test -n "$study_host"
kubectl create namespace study-node-placement --dry-run=client -o yaml | kubectl apply -f -
kubectl apply -n study-node-placement -f - <<YAML
apiVersion: apps/v1
kind: Deployment
metadata:
name: pinned
spec:
replicas: 1
selector:
matchLabels: {app: pinned}
template:
metadata:
labels: {app: pinned}
spec:
nodeSelector:
kubernetes.io/hostname: "$study_host"
containers:
- name: worker
image: busybox:1.36
command: ["sleep", "3600"]
resources:
requests: {cpu: 10m, memory: 16Mi}
limits: {cpu: 100m, memory: 64Mi}
YAML
kubectl rollout status deployment/pinned -n study-node-placement --timeout=120s
kubectl get pods -n study-node-placement -o wide
kubectl patch deployment pinned -n study-node-placement --type=merge -p '{"spec":{"template":{"spec":{"nodeSelector":null,"affinity":{"nodeAffinity":{"requiredDuringSchedulingIgnoredDuringExecution":{"nodeSelectorTerms":[{"matchExpressions":[{"key":"study.greatjin.net/missing-pool","operator":"In","values":["unavailable"]}]}]}}}}}}}'
kubectl rollout status deployment/pinned -n study-node-placement --timeout=15s || true
kubectl get pods -n study-node-placement -o wide
kubectl get events -n study-node-placement --field-selector reason=FailedScheduling
kubectl patch deployment pinned -n study-node-placement --type=merge -p "{\"spec\":{\"template\":{\"spec\":{\"affinity\":{\"nodeAffinity\":{\"requiredDuringSchedulingIgnoredDuringExecution\":{\"nodeSelectorTerms\":[{\"matchExpressions\":[{\"key\":\"kubernetes.io/hostname\",\"operator\":\"In\",\"values\":[\"$study_host\"]}]}]}}}}}}}"
kubectl rollout status deployment/pinned -n study-node-placement --timeout=120s
kubectl get pods -n study-node-placement -l app=pinned -o jsonpath='{range .items[*]}{.metadata.name}{" "}{.spec.nodeName}{"\n"}{end}'
)How to check your result
Initially confirm nodeName matches the selected worker. The impossible required label creates a Pending replacement and FailedScheduling events; an old Pod may remain available under rolling-update policy. After restoring hostname affinity, verify the replacement becomes Ready on the intended worker.
Clean up practice resources
Run after checking the result. Confirm these resources belong to your practice run and contain no data you need to keep.
kubectl delete namespace study-node-placementApply what you learned
Only zone a should be allowed, but preferred affinity lets the app run in zone b. Is this a bug?
Reveal the reasoning after trying
No: preferred is a preference. Use a required constraint for a strict requirement and inspect capacity and taints in zone a. Accept that a mandatory rule can leave Pods Pending when its requirements cannot be met.
Ready to check your understanding?
Which constraint prevents scheduling outside an approved node set?
- Only preferred affinity
- Required node affinity or nodeSelector
- Only Deployment metadata labels
- Only a Service selector
Reveal the reasoning after trying
Required node affinity or nodeSelector
Use a mandatory placement constraint. Preferred affinity can select another node, and Service selectors control traffic rather than scheduling.
Official documentation · Restrict Placement with nodeSelector and Node Affinity