Configuring Pod Affinity and Anti-Affinity

1. Using Pod Affinity

affinity:
  podAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
    - labelSelector:
        matchLabels: { app: cache }
      topologyKey: kubernetes.io/hostname
UseExample
Co-locateApp with cache on same node
Same zonetopologyKey: zone

2. Using Pod Anti-Affinity

affinity:
  podAntiAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
    - labelSelector: { matchLabels: { app: web } }
      topologyKey: kubernetes.io/hostname    # one per node (HA)
UseDetail
HASpread replicas across nodes
Noisy neighborAvoid co-locating resource hogs

3. Setting Topology Keys

topologyKeyScope
kubernetes.io/hostnamePer-node
topology.kubernetes.io/zonePer-zone
topology.kubernetes.io/regionPer-region

4. Using requiredDuringScheduling

Warning: Required pod affinity is computationally expensive at scale (O(pods × nodes)). Prefer topology spread constraints.

5. Using preferredDuringScheduling

preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
  podAffinityTerm:
    labelSelector: { matchLabels: { app: web } }
    topologyKey: kubernetes.io/hostname

6. Configuring Label Selectors

FieldUse
matchLabelsEquality
matchExpressionsSet-based

7. Setting Namespace Selectors

podAffinityTerm:
  namespaceSelector: { matchLabels: { env: prod } }
  labelSelector:    { matchLabels: { app: web } }
  topologyKey: kubernetes.io/hostname
FieldEffect
namespacesExplicit list
namespaceSelectorMatch by namespace labels
Both omittedSame namespace as pod

8. Understanding Topology Domains

A topology domain = set of nodes sharing the same value for the topologyKey label.

topologyKeyDomain count
hostname= node count
zone= AZ count

9. Combining Affinity Rules

CombinationPattern
Cache co-location + replica HApodAffinity to cache + podAntiAffinity to self
Zone redundancypodAntiAffinity zone + topology spread

10. Troubleshooting Pod Placement

SymptomCause
FailedSchedulingRequired (anti-)affinity unsatisfiable
Slow schedulingHeavy required podAffinity rules
Cross-namespace missForgot namespaceSelector