Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is topologyKey in pod affinity?

Tags:

kubernetes

I cannot really understand the purpose and usage of topologyKey in pod affinity. The documentations says:

topologyKey is the key of node labels. If two Nodes are labelled with this key and have identical values for that label, the scheduler treats both Nodes as being in the same topology. The scheduler tries to place a balanced number of Pods into each topology domain.

And example usage is as follows:

kind: Pod
metadata:
  name: with-pod-affinity
spec:
  affinity:
    podAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
          - key: security
            operator: In
            values:
            - S1
        topologyKey: topology.kubernetes.io/zone
    podAntiAffinity:
      preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        podAffinityTerm:
          labelSelector:
            matchExpressions:
            - key: security
              operator: In
              values:
              - S2
          topologyKey: topology.kubernetes.io/zone
  containers:
  - name: with-pod-affinity
    image: k8s.gcr.io/pause:2.0

So where does topology.kubernetes.io/zone come from? How can I know what value should I provide for this topologyKey field in my yaml file, and what happens if I just put a random string here? Should I label my node and use the key of this label in topologyKey field?

Thank you.

like image 334
yrazlik Avatar asked Sep 13 '25 06:09

yrazlik


1 Answers

Required as part of a affinity.podAffinity or affinity.podAntiAffinity spec section, the topologyKey field is used by the scheduler to determine the domain for Pod placement.

The topologyKey domain is used to determine relative placement of the Pods being scheduled relative to the Pods identified by the ...labelSelector.matchExpressions section.

With podAffinity, a Pod will be scheduled in the same domain as the Pods that match the expression.

Two common label options are topology.kubernetes.io/zone and kubernetes.io/hostname. Others can be found in the Kubernetes Well-Known Labels, Annotations and Taints documentation.

  • topology.kubernetes.io/zone: Pods will be scheduled in the same zone as a Pod that matches the expression.
  • kubernetes.io/hostname: Pods will be scheduled on the same hostname as a Pod that matches the expression.

For podAntiAffinity, the opposite is true: Pods will not be scheduled in the same domain as the Pods that match the expression.

The Kubernetes documentation Assigning Pods to Nodes documentation (Inter-pod affinity and anti-affinity section) provides a additional explanation.

like image 52
Drew Avatar answered Sep 15 '25 09:09

Drew