https://drive.google.com/file/d/1cuVfdChjbHgUh_AM2IMQmiVq6iKwGx-D/view?usp=sharing

πŸ” YAML Breakdown

apiVersion: v1
kind: Pod
meta
  name: nnappone
  namespace: learning
  labels:
    app: nnappone
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:  # ← HARD constraint
        nodeSelectorTerms:
        - matchExpressions:
          - key: size
            operator: In
            values:
            - small
  containers:
    - name: crackone-app
      image: nginx
      resources:
        requests:
          memory: "300Mi"
        limits:
          memory: "500Mi"

πŸ”‘ Key Section:

requiredDuringSchedulingIgnoredDuringExecution β†’ must match at schedule time, but won’t evict if node label changes later.

🎯 Rule:

"Only schedule this Pod on nodes where label size is in the list [small]."


πŸ“Œ How Node Affinity Works

Term Meaning
requiredDuringScheduling... Hard requirement β€” like nodeSelector, but more powerful
nodeSelectorTerms List of OR conditions (Pod matches if any term matches)
matchExpressions List of AND conditions (all must match within a term)
operator: In Value must be in the list (values: [small])

πŸ’‘ Other Operators:


πŸ†š nodeSelector vs requiredDuringScheduling...

Feature nodeSelector required nodeAffinity
Logic Only key=value (AND only) Supports In, NotIn, Exists, etc.
Multiple values ❌ No βœ… Yes (values: [small, medium])
Multiple keys (OR) ❌ No βœ… Yes (multiple nodeSelectorTerms)
Readability Simple More verbose, but more powerful
Future-proof Legacy Recommended by Kubernetes

βœ… Kubernetes Docs:

"We recommend using nodeAffinity instead of nodeSelector."


πŸ§ͺ Lab: Deploy Pod with Required Node Affinity

πŸ”§ Step 1: Label a Node

# 1. Get node name
kubectl get nodes

# 2. Label a node as "small"
kubectl label node minikube size=small

# 3. Verify
kubectl get nodes --show-labels | grep size

πŸ”§ Step 2: Deploy the Pod

# 1. Create namespace
kubectl create namespace learning

# 2. Apply Pod
kubectl apply -f pod-with-required-node-affinity.yml

# 3. Check placement
kubectl get pods -n learning -o wide

# βœ… Should run on node with size=small

# 4. Describe Pod β†’ see affinity rules
kubectl describe pod nnappone -n learning | grep -A 5 "Node Affinity"