Selectors and Affinity
Kubernetes gives you several tools, of increasing flexibility, for controlling which node a Pod lands on. nodeSelector is the simplest: an exact key-value label match, with no partial matching or ranking. Node affinity extends that idea with real expressions (like "in" or "greater than") and, importantly, a distinction between required rules (a hard constraint - the Pod simply will not schedule if unmet) and preferred rules (a soft hint that only influences scoring). Pod affinity works differently: instead of matching node labels, it matches other Pods, letting you say "schedule me near Pods with this label" (useful when two workloads benefit from being close, like a cache and its consumer) - and Pod anti-affinity does the reverse, spreading replicas apart across failure domains such as zones, though this can become expensive to compute and, if written as a hard requirement, can become literally unsatisfiable as clusters grow. For the common goal of "spread my replicas evenly across zones/nodes," topology spread constraints are usually a more direct and predictable tool than anti-affinity, because they describe the desired balance itself rather than a pairwise repulsion rule.
Analogy: Kubernetes is a thermostat, not a remote control. You declare the temperature; independent controllers measure reality and keep acting. Debugging means finding which sensor, rule or actuator prevents convergence.
Read the object as evidence
kubectl get RESOURCE NAME -n NAMESPACE -o yaml
kubectl describe RESOURCE NAME -n NAMESPACE
kubectl get events -n NAMESPACE --sort-by=.metadata.creationTimestamp
kubectl explain RESOURCE.spec
Do not memorize these as a ritual. The first command exposes desired and observed state, the second connects conditions and events, the third supplies a timeline, and the fourth checks the server's schema. Compare what the controller was asked to do with what it reports doing. Then test the narrowest hypothesis.
Scenario: A Deployment declares a hard (required) Pod anti-affinity rule demanding every replica land in a distinct availability zone, and it is scaled to three replicas - but the cluster only has two zones available. The third replica is left permanentlyPending, and this is not a bug: the scheduler is correctly refusing to violate a hard constraint you explicitly wrote. The real fix is a design decision - either soften the rule topreferredso it degrades gracefully under constrained capacity, or reduce the replica count to match actual zone availability.
Express preference separately from requirement
Required node affinity and nodeSelector filter candidates; preferred affinity changes scores. Pod anti-affinity can prevent replicas sharing a topology domain, while topology spread can balance skew with clearer behavior when domains are missing. Always model the number of replicas, available domains and behavior when a domain is down. Test labels with kubectl get nodes --show-labels.
Scenario: Three replicas require unique zones in a two-zone development cluster, so one never schedules. Production resilience became development deadlock. A soft rule or whenUnsatisfiable: ScheduleAnyway may fit the nonproduction objective.
Warning: Preferred rules are not guarantees. If compliance requires a node class, use required placement plus admission and verify the underlying node labels are protected from kubelet self-modification.
Production reasoning
Ask four questions: Who owns this object? What dependency must become ready next? Which controller reports the blocking condition? What evidence would disprove my current theory? This prevents symptom-driven changes. Record the context, namespace, object generation, image digest and recent rollout before mutation; a recreated Pod may erase the evidence you needed.
Warning: Running is not the same as ready, healthy, durable or correct. Kubernetes status is layered. Confirm the application-level outcome as well as the object state.
Goal: Put this model into practice in the Kubernetes lab labels-selectors. Open/labs/kubernetes, chooselabels-selectors, predict the failure path before changing anything, then use the simulator'scheckcommand to validate the finished state.
Deliberate practice
Before the lab, write the expected object relationship and the first three commands you will run. Afterward, explain why the fix converged and name one tempting change that would only mask the symptom. Repeat using an explicit namespace and a structured output format. This prediction-observation-explanation loop is what turns command familiarity into production judgment.
45-minute investigation
- Map (5 min): draw the owner-to-child chain and mark every namespace, selector, identity and dependency involved.
- Predict (5 min): write one expected status condition, one likely event and one log or metric signal before opening the lab.
- Observe (10 min): collect YAML, describe output and ordered events. Do not mutate state. Record which observation disproves your first theory.
- Repair (15 min): make the smallest declarative correction, watch the responsible controller converge, and verify the user-facing path rather than stopping at
Running. - Stress (10 min): change one relevant constraint - replica count, label, readiness, resource value or placement rule - predict the outcome, observe it, then restore the known-good declaration.
Tip: Keep a short incident note with symptom, evidence, hypothesis, change, result. Across four sections this produces a reusable runbook instead of a pile of remembered commands.