Node Affinity — Kubernetes

Always learning
2 min readAug 13, 2024

--

Node affinity is a feature in Kubernetes that allows you to constrain which nodes your pods can be scheduled on based on labels on the nodes. There are two types of node affinity rules

  1. Required
  2. Preferred

Required node affinity specifies rules that must be met for a pod to be scheduled on a node.

Preferred node affinity specifies scheduling preferences that Kubernetes will try to enforce but does not guarantee.

Node Affinity ensures that pods are hosted on particular nodes.

Pod Affinity ensures two pods are co-located in a single node.

Create a manifest file and name it as nginx-affinity.yml

apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: disktype
operator: In
values:
- ssd
containers:
- name: nginx
image: nginx

Run the manifest file

kubectl apply -f nginx-affinity.yml

Check the status of our pod

kubectl get pods

nginx pod is pending as we have attached a node affinity of type requiredDuringSchedulingIgnoredDuringExecution to our pod.

kubectl label nodes cka-cluster-worker disktype=ssd

kubectl label nodes nginx disktype=ssd

Labelled our worker node as disktype=ssd, the pod was scheduled to the worker node. Now, lets try to see on which node the pod is scheduled by running

kubectl get pods -o wide

Thank you 🙏 for taking the time to read our blog.

--

--

Always learning

கற்றுக் கொள்ளும் மாணவன்...