Node Affinity in Kubernetes: What It Is and How It Works
node affinity is a way to tell the system which nodes a pod should or should not run on based on labels on the nodes. It helps control pod placement by matching pod rules with node properties, improving workload organization and resource use.How It Works
Node affinity works like a filter that matches pods to nodes based on labels. Imagine you have a group of workers (nodes) wearing different colored hats (labels). You want to assign tasks (pods) only to workers with a specific hat color. Node affinity lets you set these rules so pods only run on nodes that meet your criteria.
There are two main types: requiredDuringSchedulingIgnoredDuringExecution, which means the pod must be scheduled on a node that matches the rules, and preferredDuringSchedulingIgnoredDuringExecution, which means the scheduler tries to place the pod on a matching node but can place it elsewhere if needed.
This system helps organize workloads by hardware, location, or other node features, making your cluster more efficient and reliable.
Example
This example shows a pod spec with node affinity that requires the pod to run on nodes labeled with disktype: ssd.
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
containers:
- name: nginx
image: nginx
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: disktype
operator: In
values:
- ssdWhen to Use
Use node affinity when you want to control where pods run based on node features. For example, you might want to run high-performance workloads only on nodes with SSD storage or place sensitive workloads on nodes in a specific data center.
It is helpful for optimizing resource use, meeting compliance rules, or improving performance by grouping similar workloads together.
Key Points
- Node affinity uses node labels to guide pod placement.
- There are required and preferred affinity rules.
- It improves workload organization and resource efficiency.
- It is set in the pod specification under
affinity.nodeAffinity.