Node Affinity

node affinity ——————→ restrict pod to be deployed on specific node.

Please note

please node ———→ Node selector and Node affinity restrict pod to be deployed on nodes that have certain labels

How to use node affinity ?

1) label node

$ kubectl label nodes node_name key=value

2) use affinity section on pod definition

spec:

containers:

affinity:

nodeAffinity:

requiredDuringSchedulingIgnoredDuringExecution:

nodeSelectorTerms:

- matchExpressions:

-key: “key“

operator: “Equal“

values


  • key: size

  • operator: Exists ————→ check if there is label on node called size


NodeAffinity Types ————————>

  • 1) Available

  • a) requiredDuringSchedulingIgnoredDuringExecution ————> means labels on nodes must be existing when deploying pod && after deployinh pod if labels is deleted or edited no worries already deployed pods will not affected.

  • b) preferedDuringSchedulingIgnoredDuringExecution —————→ means labels on nodes prefered to be existing when deploying pod if there is no labels no issue && after deployinh pod if labels is deleted or edited no worries deployed pods will not affected.

  • 2) Planned

  • requiredDuringSchedulingRequiredDuringExecution—————→ means labels on nodes must be exist before deploying pod and after deploying pod if labels are deleted or edited pod will be evicted from nodes.

    DuringScheduling —————> When create pod for first time

  • DuringExecution ———————> After deploying pod


Apply a label color=blue to node node01

——————————————————————————————————————————————————

Create a new deployment named blue with the nginx image and 3 replicas.

apiVersion: apps/v1

kind: Deployment

metadata:

name: blue

spec:

replicas: 3

selector:

matchLabels:

app: DEV

template:

metadata:

labels:

app: DEV

spec:

containers:

- name: c1

image: nginx


Set Node Affinity to the deployment to place the pods on node01 only.

Name: blue

Replicas: 3

Image: nginx

NodeAffinity: requiredDuringSchedulingIgnoredDuringExecution

Key: color

value: blue


Create a new deployment named red with the nginx image and 2 replicas, and ensure it gets placed on the controlplane node only.

Use the label key - node-role.kubernetes.io/control-plane - which is already set on the controlplane node.

apiVersion: apps/v1

kind: Deployment

metadata:

name: red

spec:

replicas: 2

selector:

matchLabels:

app: Test

template:

metadata:

labels:

app: Test

spec:

containers:

- name: c1

image: nginx

affinity:

nodeAffinity:

requiredDuringSchedulingIgnoredDuringExecution:

nodeSelectorTerms:

- matchExpressions:

- key: node-role.kubernetes.io/control-plane

operator: Exists

0
Subscribe to my newsletter

Read articles from Esraa Elhasanen Soror directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Esraa  Elhasanen Soror
Esraa Elhasanen Soror