Kubernetes: Kubernetes Node Affinity Example-DecodingDevOps

Kubernetes Node Affinity Example-DecodingDevOps

Kubernetes automatically schedules your application based on the current status of node resources utilization which will make sure that every node’s resource utilization is balanced. But sometimes you want to schedule your application in a specific node/s.

What is Kubernetes Node Affinity

Node Affinity is a way for the scheduler to know where a pod should be scheduled. The concept behind this is we attach a label to the node, to differentiate it from the other nodes. And then we can use that label as a selector in the deployment manifest file to strictly schedule the pods on that node. All rules should be matched while scheduling the pod. If it doesn’t match the rule then the pod won’t be scheduled. Its will stay in pending state.

Kubernetes Node Affinity Example

Creating a deployment with node Affinity.

cat nodeaffinity.yml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: env
                operator: In
                values:
                - production
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80

Use the below command to create a deployment

kubectl apply -f nodeaffinity.yml

Here, we have specified nodeAffinity. If any node contains label which has the key: env with value: production deployment will be scheduled there. After creating the deployment, your pods will be in pending state. Because we don’t have any node with the nodeAffinity which match our specification file.

You can verify the pods are in pending state using the command shown below.

kubectl get pod -o wide

Assigning a Label to the Node

Now let’s assign label to a node so that the pod can be scheduled on a node.

To assign a label use the command shown below. (Change the node name to match the node you have)

kubectl label nodes <your-node> env=production

You  can see the pods are in container creating state by executing the command below.

kubectl get pod -o wide

You can also create node labels while creating new instance group.

Pro-Tip:

While running your production cluster you should keep production and deployment nodes different. We need production node to be available all the time. Whereas we dont want so much higher availability of development nodes, So we can run development nodes on spot instance which will help us reduce the cost of the infrastructure.

  • kubernetes node affinity example
  • kubernetes nodeaffinity
  • node affinity kubernetes