How to Use nodeSelector in Pod in Kubernetes
Use
nodeSelector in a pod's spec to schedule the pod on nodes with matching labels. Add nodeSelector as a key-value map under spec in the pod YAML to specify node labels for pod placement.Syntax
The nodeSelector field is a simple key-value map under the pod's spec. Each key-value pair matches a label on nodes. Kubernetes schedules the pod only on nodes with all matching labels.
- spec: Pod specification section.
- nodeSelector: Map of node label keys and values.
- Keys and values must exactly match node labels.
yaml
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
nodeSelector:
disktype: ssd
region: us-west
containers:
- name: nginx
image: nginxExample
This example shows a pod that will only run on nodes labeled with disktype=ssd and region=us-west. Kubernetes checks node labels and schedules the pod accordingly.
yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
spec:
nodeSelector:
disktype: ssd
region: us-west
containers:
- name: nginx
image: nginx:1.23Output
pod/nginx-pod created
Common Pitfalls
Common mistakes when using nodeSelector include:
- Using keys or values that do not match any node labels, causing pods to stay pending.
- Forgetting to label nodes before using
nodeSelector. - Using
nodeSelectorwhen more flexible scheduling is needed (considernodeAffinityinstead).
yaml
apiVersion: v1
kind: Pod
metadata:
name: wrong-pod
spec:
nodeSelector:
wrongkey: wrongvalue
containers:
- name: nginx
image: nginx
---
apiVersion: v1
kind: Pod
metadata:
name: correct-pod
spec:
nodeSelector:
disktype: ssd
containers:
- name: nginx
image: nginxQuick Reference
- nodeSelector: Simple key-value map for node labels.
- Pods schedule only on nodes matching all labels.
- Use
kubectl label nodes <node-name> <key>=<value>to add labels. - For complex rules, use
nodeAffinity.
Key Takeaways
Use nodeSelector in pod spec to schedule pods on nodes with matching labels.
Node labels must exist and exactly match the nodeSelector keys and values.
Pods won't schedule if no nodes match the nodeSelector labels.
Label nodes with kubectl before using nodeSelector.
For advanced scheduling, consider nodeAffinity instead of nodeSelector.