This article guides you through implementing node affinity in Kubernetes for controlled pod scheduling.
In this lesson, we will guide you through a practical lab exercise focused on implementing node affinity in Kubernetes. By following these steps, you will learn how to inspect node labels, add custom labels, and apply node affinity rules to your deployments for controlled pod scheduling.
Step 4. Apply Node Affinity to the “blue” Deployment
To ensure that the pods in the blue deployment only run on node01 (which now has the label color=blue), update the deployment with a node affinity rule. Edit the deployment YAML and incorporate the following affinity configuration under the template.spec section:
Copy
Ask AI
apiVersion: apps/v1kind: Deploymentmetadata: name: blue labels: app: bluespec: replicas: 3 selector: matchLabels: app: blue strategy: type: RollingUpdate template: metadata: labels: app: blue spec: affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: color operator: In values: - blue containers: - name: nginx image: nginx imagePullPolicy: Always resources: {} dnsPolicy: ClusterFirst restartPolicy: Always
After saving the changes, the scheduler will enforce that all pods for the blue deployment are placed on node01. Verify the updated placement with:
Step 5. Create Deployment “red” with Two Replicas on the Control Plane
Now, create a deployment named red that targets the control plane node. The control plane is typically identified by the label node-role.kubernetes.io/master (which exists without a value).Start by generating the deployment YAML using a dry run:
Create a deployment (blue) and configure node affinity to restrict its pods to the node with the matching label.
Use a dry run to generate a deployment YAML for red and apply a node affinity rule so that its pods are scheduled exclusively on the control plane node (by verifying the existence of node-role.kubernetes.io/master).
By following these steps, you can ensure optimal pod placement and efficient use of your Kubernetes cluster resources. Happy deploying!For more details, check out the following resources: