Mastering Kubernetes Node Affinity: A Deployment Example
In the dynamic world of container orchestration, Kubernetes offers a powerful feature called node affinity to influence the scheduling of pods onto nodes. This article walks you through a comprehensive example of Kubernetes node affinity deployment, ensuring your applications run on the most suitable nodes.
Understanding Kubernetes Node Affinity
Node affinity in Kubernetes allows you to specify that a pod should run in nodes that satisfy certain conditions. It helps in achieving high availability, fault tolerance, and efficient resource utilization. There are two types of node affinity: required and preferred.
- Required: If not satisfied, the scheduler will not place the pod in any node.
- Preferred: The scheduler will try to place the pod in nodes that satisfy the affinity, but it's not mandatory.
Node Affinity Labels
Before diving into the example, let's understand node affinity labels. You can add labels to your nodes using the `kubectl label` command. For instance, to add a label 'disktype:ssd' to a node named 'my-node', use:

kubectl label nodes my-node disktype=ssd
Example: Deploying a Pod with Node Affinity
Let's create a deployment with a pod that has a required node affinity to run only on nodes with the label 'disktype:ssd'.
Step 1: Create a Node with the Required Label
First, ensure you have a node with the required label. You can create a node using a Kubernetes manifest:
apiVersion: v1
kind: Node
metadata:
name: my-node
labels:
disktype: ssd
Step 2: Create the Deployment YAML
Create a deployment YAML file (e.g., `deployment.yaml`) with the following content:

| Field | Description |
|---|---|
| affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution | Defines the required node affinity. |
| nodeSelectorTerms | Contains the list of node selector terms. |
| matchExpressions | Defines the match expressions for the node selector. |
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-deployment
spec:
replicas: 1
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: disktype
operator: In
values:
- ssd
containers:
- name: my-container
image: my-image:latest
Step 3: Apply the Deployment
Apply the deployment using `kubectl apply`:
kubectl apply -f deployment.yaml
Verifying the Deployment
After applying the deployment, you can verify that the pod is running on the node with the 'disktype:ssd' label using:
kubectl get pods -o wide
Conclusion
In this article, we explored Kubernetes node affinity, its types, and labels. We also walked through an example of deploying a pod with required node affinity. Understanding and utilizing node affinity can significantly enhance your Kubernetes cluster's efficiency and reliability.























