Pods 对 StatefulSet 中不同节点的亲和度

Pods affinity to different nodes in StatefulSet

我正在创建 StatefulSet,我希望 pods 在一个 StatefulSet 中分布在 k8s 集群的不同节点上。在我的例子中 - 一个 StatefulSet 是一个数据库副本集。

sts.Spec.Template.Labels["mydb.io/replicaset-uuid"] = replicasetUUID.String()
sts.Spec.Template.Spec.Affinity.PodAntiAffinity = &corev1.PodAntiAffinity{
    RequiredDuringSchedulingIgnoredDuringExecution: []corev1.PodAffinityTerm{
        {
            LabelSelector: &metav1.LabelSelector{
                MatchExpressions: []metav1.LabelSelectorRequirement{
                    {
                        Key:      "mydb.io/replicaset-uuid",
                        Operator: metav1.LabelSelectorOpIn,
                        Values:   []string{replicasetUUID.String()},
                    },
                },
            },
            TopologyKey: "kubernetes.io/hostname",
        },
    },
}

但是,通过这些设置,我得到了相反的结果。 storage-0-0storage-0-1 在同一个副本集和同一个节点上...

而且,他们有完全相同的标签mydb.io/replicaset-uuid

$ kubectl -n mydb get pods -o wide
NAME                             READY   STATUS    RESTARTS   AGE   IP        NODE                           NOMINATED NODE   READINESS GATES
storage-0-0                      1/1     Running   0          40m   x.x.x.x   kubernetes-cluster-x-main-0    <none>           <none>
storage-0-1                      1/1     Running   0          39m   x.x.x.x   kubernetes-cluster-x-main-0    <none>           <none>
storage-1-0                      1/1     Running   0          40m   x.x.x.x   kubernetes-cluster-x-slave-0   <none>           <none>
storage-1-1                      1/1     Running   0          40m   x.x.x.x   kubernetes-cluster-x-slave-0   <none>           <none>
mydb-operator-58c9bfbb9b-7djml   1/1     Running   0          46m   x.x.x.x   kubernetes-cluster-x-slave-0   <none>           <none>

我建议在 statefulset 定义中使用 podAntiAffinity 规则来部署您的应用程序,这样不会有两个实例位于同一主机上。

参考:An example of a pod that uses pod affinity

它工作正常,正如@jesmart 在评论中写道:

The description of the problem works correctly I just indicated the wrong image with the application