What is Kubernetes node affinity and pod affinity?

Answer

Kubernetes scheduling affinity controls where pods are placed: Node Affinity: prefer or require pods to be scheduled on nodes with specific labels. More expressive than nodeSelector: affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: # Hard requirement nodeSelectorTerms: - matchExpressions: - key: kubernetes.io/arch operator: In values: [amd64] preferredDuringSchedulingIgnoredDuringExecution: # Soft preference - weight: 100 preference: matchExpressions: - key: node-type operator: In values: [compute-optimized]. Taints and Tolerations: taints mark a node so pods won't be scheduled there unless they tolerate the taint. Used to dedicate nodes for specific workloads or mark nodes for special conditions. kubectl taint nodes gpu-node dedicated=gpu:NoSchedule # Taint kubectl taint nodes gpu-node dedicated=gpu:NoSchedule- # Remove. Pod toleration: tolerations: - key: dedicated value: gpu operator: Equal effect: NoSchedule. Taint effects: NoSchedule (don't schedule), PreferNoSchedule (avoid), NoExecute (evict existing pods without toleration). Pod Affinity/Anti-affinity: schedule pods based on where OTHER pods are running. Affinity: "schedule my app pods on nodes where Redis pods are running" (reduce latency). Anti-affinity: "spread replicas across nodes" (high availability). affinity: podAntiAffinity: requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchLabels: app: my-app topologyKey: kubernetes.io/hostname # Don't schedule on same node. topologySpreadConstraints: modern replacement for pod anti-affinity — evenly spread pods across zones/nodes: topologySpreadConstraints: - maxSkew: 1 topologyKey: topology.kubernetes.io/zone whenUnsatisfiable: DoNotSchedule labelSelector: matchLabels: app: my-app.