AWS Community Builders  profile image Hari Karthigasu

Kubernetes 拓扑分布约束允许 Pod 均匀分布在节点、区域和可用区之间。

以下 TopologySpreadConstraints 可确保任意时刻任意两个节点间的 Pod 数量差值不超过 2。

示例:如果你在 3 个节点上运行 5 个 Pod,Kubernetes 调度器会根据 topologyKey: kubernetes.io/hostname 将它们调度为 1:1:32:2:1 两种形式

option 1: 最大差值为 3-1=2
option 2: 最大差值为 2-1=1

Enter fullscreen mode Exit fullscreen mode

它永远不会被调度为 3:2:0,因为最大差值会达到 3-0=3

如果条件不满足,Pod 将不会被调度。 whenUnsatisfiable: DoNotSchedule

同样地,我们可以定义多条约束。调度器会对它们执行 AND 操作以找出最优组合。

      topologySpreadConstraints:
      - maxSkew: 2
        topologyKey: kubernetes.io/hostname
        whenUnsatisfiable: DoNotSchedule
        labelSelector:
          matchLabels:
            app.kubernetes.io/application: backend
            app.kubernetes.io/name: backend
_      # 将 maxSkew 设为 1 可确保 Pod(几乎)均匀分布在各可用区。  _      
      - maxSkew: 1
        topologyKey: topology.kubernetes.io/zone
_        # 将 whenUnsatisfiable 设为 ScheduleAnyway 可确保在可用区故障或资源不足时,Pod 仍能被调度到活跃的可用区,从而绕过 maxSkew 限制。_
        whenUnsatisfiable: ScheduleAnyway
        labelSelector:
          matchLabels:
            app.kubernetes.io/application: backend
            app.kubernetes.io/name: backend

Enter fullscreen mode Exit fullscreen mode