0
0
Kubernetesdevops~30 mins

Pod affinity and anti-affinity in Kubernetes - Mini Project: Build & Apply

Choose your learning style9 modes available
Pod Affinity and Anti-Affinity in Kubernetes
📖 Scenario: You are managing a Kubernetes cluster for a small online store. You want to control how pods are placed on nodes to improve reliability and performance.Specifically, you want some pods to be placed together (affinity) and some pods to be placed apart (anti-affinity).
🎯 Goal: Learn how to write pod specifications with affinity rules using podAffinity and podAntiAffinity in Kubernetes pod manifests.You will create a pod manifest with labels, then add affinity and anti-affinity rules, and finally check the pod spec output.
📋 What You'll Learn
Create a pod manifest with specific labels
Add pod affinity rules to schedule pods together
Add pod anti-affinity rules to avoid scheduling pods together
Print the final pod manifest YAML
💡 Why This Matters
🌍 Real World
Pod affinity and anti-affinity help control pod placement in Kubernetes clusters to improve availability and performance by grouping or separating pods.
💼 Career
Understanding pod affinity rules is important for Kubernetes administrators and DevOps engineers to optimize workload distribution and fault tolerance.
Progress0 / 4 steps
1
Create a basic pod manifest with labels
Create a YAML manifest for a pod named web-server in namespace default. The pod should have a container named nginx using image nginx:latest. Add labels app: web and tier: frontend under metadata.labels.
Kubernetes
Need a hint?

Use metadata.labels to add labels. Containers go under spec.containers.

2
Add pod affinity to schedule pods together
Add a podAffinity rule under spec.affinity to require scheduling this pod on nodes where pods with label app: web are already running. Use requiredDuringSchedulingIgnoredDuringExecution with topologyKey: kubernetes.io/hostname.
Kubernetes
Need a hint?

Put podAffinity under spec.affinity. Use requiredDuringSchedulingIgnoredDuringExecution with a list of rules.

3
Add pod anti-affinity to avoid scheduling pods together
Add a podAntiAffinity rule under spec.affinity to avoid scheduling this pod on nodes where pods with label tier: frontend are running. Use preferredDuringSchedulingIgnoredDuringExecution with weight 100 and topologyKey: kubernetes.io/hostname.
Kubernetes
Need a hint?

Put podAntiAffinity under spec.affinity. Use preferredDuringSchedulingIgnoredDuringExecution with weight and podAffinityTerm.

4
Print the final pod manifest YAML
Print the complete pod manifest YAML with the affinity and anti-affinity rules included.
Kubernetes
Need a hint?

Use a print statement to confirm the manifest is ready.