Node Affinity is a feature in Kubernetes that allows you to control the placement of pods on specific nodes based on defined criteria. It provides more flexibility compared to traditional nodeSelector
.
What is Node Affinity? ๐ค
Node Affinity helps schedule pods on nodes that match specific criteria using node labels. It includes two types of rules:
Required (Hard): Pods must be scheduled on matching nodes.
Preferred (Soft): Pods prefer matching nodes but can still run on other nodes.
How Does Node Affinity Work? โ๏ธ
Node Affinity rules are defined in the spec.affinity
section of a pod manifest. It uses node labels to identify matching nodes. There are two key rules:
requiredDuringSchedulingIgnoredDuringExecution
: The pod will only run on nodes satisfying the rule.preferredDuringSchedulingIgnoredDuringExecution
: The pod prefers matching nodes but can fall back to others.
Step-by-Step Implementation with Commands ๐ ๏ธ
1. Label Nodes for Testing
Start by labeling nodes to simulate a real-world scenario:
kubectl label nodes <node-name> disktype=ssd
kubectl label nodes <node-name> region=us-east
Verify the labels:
kubectl get nodes --show-labels
2. Create a Pod Manifest with Node Affinity
Below is a pod manifest with both required and preferred node affinity rules:
apiVersion: v1
kind: Pod
metadata:
name: web-app
labels:
app: web
spec:
containers:
- name: nginx
image: nginx
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: disktype
operator: In
values:
- ssd
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 1
preference:
matchExpressions:
- key: region
operator: In
values:
- us-east
Apply the manifest:
kubectl apply -f pod-affinity.yml
3. Check Pod Scheduling
To verify if the pod is scheduled on the desired node:
kubectl get pods -o wide
This command shows the node where the pod is running.
4. Test Node Affinity Behavior
To test the hard constraints, try removing the required label from the node:
kubectl label nodes <node-name> disktype-
Youโll notice that the pod wonโt be scheduled because no nodes match the required affinity rule.
For soft constraints, the pod will prefer nodes in the us-east
region but can still run on other nodes.
Conclusion ๐
Node Affinity provides a flexible way to schedule workloads in Kubernetes. With commands and labels, you can ensure pods are deployed on the right nodes for optimal performance and resource utilization. This approach is ideal for workloads requiring specific hardware, regions, or compliance needs.
Let me know if youโd like additional examples or further refinements! ๐