liveBook · Manning

Affinity

As explained in Google Anthos in Action

Node affinity is a Kubernetes scheduling constraint that selects nodes through label expressions and required or preferred matching behavior.

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

How Google Anthos in Action covers it

How deep it goes
Works through label expressions and a required node-affinity Pod manifest, while leaving custom scheduler implementation outside its scope.
Examples
Shows a Pod restricted to two zones through an In expression and supplies kubectl commands for checking node labels and Pod placement.
What it assumes
Assumes working familiarity with Pods, deployment manifests, node labels, and basic Kubernetes scheduling.
What you can do after
Apply it via Kubernetes Pod manifests to constrain eligible nodes with label expressions and inspect placement with kubectl.
How it connects
Connects node labels and label selectors to the Kubernetes scheduler, taints and tolerations, and Pod affinity and anti-affinity.

Also explained in

Compare how 6 books explain affinity →

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.