← Back to list

k8s: spread pod using podAntiAffinity vs topologySpreadConstraints

I used to force gitlab-runner to different node using podAntiAffinity

John Zen · 2024-09-17 11:28 · 3 claps · 0.4 min read
#kubernetes #pod-anti-affinity #topologyspreadconstraint #gitlab
Open on Medium ↗
Wiki topics: TLS · Design Tools & Workflow ☁️ · DevOps & Cloud 🔓 · Open Source 📐 · Mathematics

k8s: spread pods using podAntiAffinity vs topologySpreadConstraints

I used to force gitlab-runner to different node using podAntiAffinity

kind: Deployment
metadata:
  name: gitlab-runner
spec:
  ...
  template:
    ...
    spec:
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              labelSelector:
                matchExpressions:
                - key: "app"
                  operator: "In"
                  values:
                  - "gitlab-runner"
              topologyKey: "kubernetes.io/hostname"

This forces each gitlab-runner pod to different node

Using topologySpreadConstraints , I can spread pods among nodes. e.g.

  • node 1: 3 pods running
  • node 2: 4 pods running
apiVersion: apps/v1
kind: Deployment
metadata:
  name: gitlab-runner
spec:
  ...
  template:
    ...
    spec:
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: DoNotSchedule
          labelSelector:
            matchLabels:
              app: gitlab-runner

메타데이터
post_id
0752f4dbdbbd
slug
k8s-spread-pod-using-podantiaffinity-vs-topologyspreadconstraints-0752f4dbdbbd
url
https://medium.com/@john.shaw.zen/k8s-spread-pod-using-podantiaffinity-vs-topologyspreadconstraints-0752f4dbdbbd
canonical_url
https://medium.com/@john.shaw.zen/k8s-spread-pod-using-podantiaffinity-vs-topologyspreadconstraints-0752f4dbdbbd
author_url
https://medium.com/@john.shaw.zen
status
ok
fetched_at
2026-08-29 00:13:12