How do you distribute pods across different nodes in Kubernetes?
sobes.tech AI
Answer from AI
There are several approaches to distribute pods across different nodes in Kubernetes:
-
nodeSelector — a simple way to specify on which nodes a pod can run, using node labels.
-
affinity/anti-affinity — a more flexible mechanism that allows setting rules for preferences and obligations regarding pod placement relative to nodes or other pods.
-
PodTopologySpread — controls the distribution of pods across topology domains (e.g., nodes) to avoid concentration.
-
Taints and Tolerations — allow marking nodes and permitting pods to run only with the corresponding tolerations.
Example of using anti-affinity to spread pods across different nodes:
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- myapp
topologyKey: "kubernetes.io/hostname"
containers:
- name: mycontainer
image: myimage
This rule prevents pods with the label app: myapp from running on the same node, ensuring their distribution.