In this lesson, you will learn how to direct the Kubernetes scheduler to place your Pods on specific nodes using Node Selectors and Affinity rules.
By default, the Kubernetes scheduler decides where to place your Pods based on resource availability. However, real-world clusters often have heterogeneous hardware—perhaps you have some nodes with GPUs, or some nodes that are located in a specific data center zone. When your application needs specific hardware or proximity, you must guide the scheduler.
Node Selectors
The simplest way to restrict Pod placement is via nodeSelector. This allows you to label your nodes and then instruct the Pod to only land on nodes that match that label.
spec:
nodeSelector:
disktype: ssd
If you add this to your Pod spec, the scheduler will only consider nodes that have the label disktype=ssd. If no such node exists, the Pod will remain in a Pending state.
Affinity Rules
While nodeSelector is binary (it either matches or it doesn’t), Affinity provides more expressive, "human-like" logic. It allows for "soft" preferences.
- RequiredDuringSchedulingIgnoredDuringExecution: Similar to a selector; the Pod must land on a matching node.
- PreferredDuringSchedulingIgnoredDuringExecution: The scheduler will try to place the Pod on a matching node, but if it can’t, it will settle for a less ideal one rather than leaving the Pod pending.
Here is an example of a "required" affinity rule:
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: topology.kubernetes.io/zone
operator: In
values:
- us-east-1a
Using these tools, you transform the scheduler from a blind automated process into a precision instrument that respects your infrastructure requirements. You are essentially adding metadata to your hardware, then writing "if-then" statements in your Pod configuration to ensure your code runs exactly where it belongs.
Key Takeaway: Use Node Selectors for strict, simple requirements and Affinity rules for complex, flexible scheduling logic to ensure your Pods always land on the most appropriate hardware.