liveBook · Manning

Anti-affinity

As explained in Google Anthos in Action

Pod anti-affinity is a Kubernetes scheduling constraint that prevents a pod from sharing a selected topology domain with matching existing pods.

Pod anti-affinity controls placement relative to other Pods. Instead of targeting a node by its labels, it matches existing Pods by label and identifies a topology domain where the new Pod should avoid joining them. Use it when replicas should be spread rather than placed together. section 3.2.7

A rule has three practical parts:

  • A label selector identifies the Pods to avoid. In the frontend example, it matches Pods labeled `app=nginx-frontend`. section 3.2.7
  • A `topologyKey` defines what counts as together. The example uses a zone label, so the placement preference concerns zones rather than individual nodes. section 3.2.7
  • A scheduling preference determines how strongly placement is constrained. The example uses `preferredDuringSchedulingIgnoredDuringExecution`: it expresses a preference, not a guarantee of separation. section 3.2.7
apiVersion: v1
kind: Pod
metadata:
name: nginx-frontend-antiaffinity-example
spec:
podAntiAffinity:
 preferredDuringSchedulingIgnoredDuringExecution:
  podAffinityTerm:
   labelSelector:
    matchExpressions:
    - key: app
     operator: In
     values:
     - nginx-frontend
   topologyKey: failure-domain.beta.kubernetes.io/zone
containers:
- name: nginx-frontned
 image: bitnami/nginx

Inspect the frontend example for its Pod label selector, zone topology key, and preferred anti-affinity rule. Treat the listing as an illustration of those fields, not a copy-ready manifest. section 3.2.7

Choose anti-affinity for Pod-to-Pod separation. Node affinity and node selectors instead target nodes by their labels; taints and tolerations provide another way to control which workloads a node accepts. Check the intended topology and matching labels before relying on a placement preference. section 3.2.7 section 3.5

How Google Anthos in Action covers it

How deep it goes
Illustrates a preferred rule through a label selector and topology key, without developing a full copy-ready deployment procedure.
Examples
Uses an `app=nginx-frontend` selector and a zone topology key to illustrate preferred separation of frontend Pods.
What it assumes
Assumes familiarity with Pods, nodes, labels, and manifests while introducing their roles in scheduling controls.
What you can do after
Apply it via Kubernetes Pod configuration to express a placement preference against zones containing matching Pods.
How it connects
Connects Pod label selectors and topology keys to affinity, node selectors, taints, and tolerations as scheduling controls.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Google Anthos in Action. The section links point to the parts of the book it draws on.