In this lesson, you will learn how to balance strict placement requirements with flexible "best-effort" preferences to gain finer control over where your Kubernetes Pods land.
While we previously looked at simple nodeSelector options, Kubernetes provides more powerful tools called Node Affinity. Think of Node Affinity as a way to give the scheduler a "must-have" checklist versus a "nice-to-have" wish list.
Hard Constraints: requiredDuringSchedulingIgnoredDuringExecution
Think of this as a hard requirement. If you tell Kubernetes that a Pod must be on a node with an ssd=true label, the scheduler will strictly refuse to place that Pod anywhere else. If no such node is available, the Pod will simply stay in a Pending state. Use this when your application absolutely requires specific hardware, such as a GPU or high-speed local storage, to function correctly.
Soft Constraints: preferredDuringSchedulingIgnoredDuringExecution
Think of this as a soft preference or a "best-effort" suggestion. You are telling the scheduler: "I would prefer this Pod to be on a node in region=us-east-1, but if that isn't possible, put it anywhere else that is available." This allows your cluster to remain highly available by keeping your services running even when your preferred nodes are fully utilized.
Here is how these look in your YAML configuration:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: hardware
operator: In
values: ["ssd"]
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 1
preference:
matchExpressions:
- key: zone
operator: In
values: ["zone-1"]
By combining these, you create a robust scheduling strategy: the hard constraint ensures your application meets its technical prerequisites, while the soft constraint optimizes the Pod's placement to favor your preferred environment without sacrificing availability.
Key Takeaway: Hard constraints act as non-negotiable mandates for deployment, while soft constraints offer flexible guidance to the scheduler to optimize performance when capacity allows.