What is Node Selector in Kubernetes?
- Kubernetes uses labels on nodes
- Pod uses nodeSelector to match those labels
- Pod will only run on nodes that match labels
In Kubernetes, both nodes and pods use labels to control where workloads run. A node is first assigned a label such as disktype=ssd, which describes its characteristics. Then, when creating a pod, you specify a nodeSelector with the same key-value pair (disktype=ssd). The Kubernetes scheduler compares the pod’s selector with the available node labels. If a node has a matching label, the scheduler places (runs) the pod on that node. However, if no node in the cluster has the required label, Kubernetes cannot find a suitable node, so the pod remains in a Pending state until a matching node becomes available.
Step 1: Check available nodes
kubectl get nodes
Step 2: Add label to a specific node
kubectl label nodes node1 disktype=ssd
Verify label:
kubectl get nodes --show-labels
Step 3: Create Pod YAML with nodeSelector
vi pod.yaml
apiVersion: v1kind: Podmetadata: name: nginx-ssdspec: containers: - name: nginx image: nginx nodeSelector: disktype: ssd
Node: Pod will only run on nodes that have “disktype: ssd”
Step 4: Apply Pod
kubectl apply -f pod.yaml
Step 5: Verify pod is running on correct node
kubectl get pods -o wide
If no node matches then pod status show as pending state. Kubernetes only schedules when labels match
Example:
Example (SSD node scheduling)
🎯 Scenario (Real-world)
You have a Kubernetes cluster with 2 nodes:
node1→ high performance (SSD disk)node2→ normal storage (HDD)
You want your application (pod) to run only on the SSD node for better performance (like DB, analytics, etc.).
1. Check the available nodeskubectl get nodes2. Label the nodekubectl label nodes node1 disktype=ssd3. Verify the node labelkubectl get nodes --show-labels4. Create Pod YAML and used node selector in itvi pod1.yamlapiVersion: v1kind: Podmetadata: name: nginx-ssdspec: containers: - name: nginx image: nginx nodeSelector: disktype: ssd5. Deploy the PODkubectl apply -f pod1.yaml6. Verify where pod is runningkubectl get pods -o wide
Explanation
In this example, the node node1 was labeled with disktype=ssd, which describes its capability. When the pod was created, the nodeSelector field specified the same label (disktype=ssd). The Kubernetes scheduler compared the pod’s requirement with the available nodes and found that only node1 satisfied this condition. As a result, the pod was successfully scheduled and started on node1. If no node had the matching label, Kubernetes would not have been able to schedule the pod, and it would have remained in a Pending state until a suitable node became available