https://drive.google.com/file/d/1L94T05RDk0_rnE1lBvR1q804MPaiDhBp/view?usp=sharing

πŸ”§ Corrected & Modernized YAML

apiVersion: apps/v1                  # βœ… Modern API (extensions/v1beta1 is DEPRECATED)
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx                    # βœ… Required in apps/v1
  template:
    metadata:
      labels:
        app: nginx
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - topologyKey: kubernetes.io/hostname
            labelSelector:
              matchLabels:
                app: nginx          # ← Avoid nodes running Pods with this label
      containers:                    # βœ… Plural "containers" (was "container")
        - name: nginx
          image: nginx:1.25-alpine   # βœ… Avoid :latest
          ports:
            - containerPort: 80

πŸ”‘ Key Fixes:


πŸ“Œ How Anti-Affinity Works in Deployments

Field Purpose
podAntiAffinity "Don’t schedule on nodes that match this rule"
labelSelector.matchLabels Target your own Pods (app: nginx)
topologyKey: kubernetes.io/hostname Scope = same node
requiredDuringScheduling... Hard rule β€” must spread Pods

🎯 Your Rule:

"Do NOT schedule two nginx Pods on the same node."

πŸ’‘ Why This Matters:


πŸ§ͺ k3s Lab: Verify Anti-Affinity Spread

βœ… Assumption: You have β‰₯3 worker nodes in your k3s cluster.

(If you have only 2 nodes, reduce replicas: 2)

πŸ”§ Step 1: Deploy the Fixed YAML

# Save as deployment-with-anti-affinity-fixed.yaml
kubectl apply -f deployment-with-anti-affinity-fixed.yaml

# Wait for Pods to be ready
kubectl get pods -l app=nginx -o wide

πŸ”§ Step 2: Verify Pod Distribution

# Check node distribution
kubectl get pods -l app=nginx -o wide

# βœ… Expected (on 3-node cluster):
# NAME                     READY   NODE
# nginx-7df8b9b5d4-abc12   1/1     k3s-node1
# nginx-7df8b9b5d4-def34   1/1     k3s-node2
# nginx-7df8b9b5d4-ghi56   1/1     k3s-node3

# ❌ If you see 2 Pods on same node β†’ anti-affinity failed!

πŸ”§ Step 3: Test Failure (Not Enough Nodes)

πŸ’‘ If you have only 2 nodes but replicas: 3:

# One Pod will stay Pending!
kubectl get pods -l app=nginx

# Describe to confirm
kubectl describe pod <pending-pod>
# Events: 0/2 nodes available: 2 node(s) didn't match pod anti-affinity rules.

πŸ” Solution: