Combining Multiple Affinity Terms
What you'll learn: How to use AND and OR logic to combine multiple node affinity expressions for fine-grained scheduling control.
Understanding Compound Affinity Logic
Node affinity becomes truly powerful when you combine multiple conditions. Think of it like apartment hunting with a detailed wishlist: you might need a dishwasher AND parking (both required), OR prefer a balcony OR a fireplace (either nice to have).
In Kubernetes, you can layer multiple affinity rules to express complex scheduling requirements. The structure naturally creates logical relationships:
- Multiple
nodeSelectorTerms= OR logic – Any term matching satisfies the requirement - Multiple
matchExpressionswithin one term = AND logic – All expressions in that term must match
How It Works
When you specify requiredDuringSchedulingIgnoredDuringExecution, you can list multiple nodeSelectorTerms. The scheduler will place the Pod on any node that matches at least one complete term.
Within each term, you can have multiple matchExpressions. For that term to match, all expressions must be true on the target node.
This creates a flexible "OR of ANDs" pattern: (Expression1 AND Expression2) OR (Expression3 AND Expression4).
Practical Example Pattern
A Pod needing SSD storage AND high memory, OR alternatively GPU capability:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions: # Term 1: SSD AND high-memory
- key: storage
operator: In
values: ["ssd"]
- key: memory
operator: In
values: ["high"]
- matchExpressions: # Term 2: GPU present
- key: gpu
operator: Exists
Key Takeaway: Combine multiple affinity terms to express "OR" logic between term groups, while multiple expressions within a term create "AND" logic—giving you precise control over node selection criteria.