Node affinity constrains where Kubernetes can place a Pod by matching expressions against node labels. Use it when a workload needs a particular class of nodes, such as nodes with specialized hardware, rather than leaving placement entirely to the scheduler. section 3.2.7
Define node labels on the nodes and a node-affinity rule in the Pod manifest. A required rule limits eligible nodes during scheduling; a preferred rule expresses a softer placement preference. If a required rule matches no suitable node, the scheduler cannot place the Pod. section 3.2.7
apiVersion: v1
kind: Pod
metadata:
name: nginx-affinity
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: failure-domain.beta.kubernetes.io/zone
operator: In
values:
- us-central1-a
- us-central1-c
containers:
- name: nginx-affinity
image: bitnami/nginx
This Pod uses requiredDuringSchedulingIgnoredDuringExecution with an In expression to require a node whose zone label is us-central1-a or us-central1-c. section 3.2.7
Choose the expression operator to fit the label test: In and NotIn compare values with a list, Exists and DoesNotExist test for a label, and Gt and Lt compare numeric values. Check available labels with kubectl get nodes --show-labels, then inspect placement with kubectl get pods -o wide. section 3.2.7
Node affinity attracts Pods to labeled nodes; it does not, by itself, reject unrelated Pods from those nodes. Use taints and tolerations when nodes must repel workloads, and use Pod affinity or anti-affinity when placement depends on other Pods rather than node labels. section 3.2.7





