在 Kubernetes 中,可以使用 NodeAffinity 字段来指定 Pod 的亲和性调度规则,NodeAffinity 是一个结构体,其中包含两个属性:
- requiredDuringSchedulingIgnoredDuringExecution: 在调度阶段必须满足的亲和性规则。
- preferredDuringSchedulingIgnoredDuringExecution: 优先级较低的亲和性规则。
下面是一个使用 golang NodeAffinity 进行亲和性调度的例子:
import (
"k8s.io/api/core/v1"
)
// 创建 PodSpec 对象
podSpec := &v1.PodSpec{
...
Affinity: &v1.Affinity{
NodeAffinity: &v1.NodeAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{ // 必须满足以下标签要求
NodeSelectorTerms: []v1.NodeSelectorTerm{
{
MatchExpressions: []v1.NodeSelectorRequirement{
{
Key: "zone",
Operator: v1.NodeSelectorOpIn,
Values: []string{"cn-east-01", "cn-east-02"},
},
},
},
},
},
PreferredDuringSchedulingIgnoredDuringExecution: nil, // 暂不需要优先级较低的亲和性规则
},
},
}
// 创建 Pod 对象
pod := &v1.Pod{
...
Spec: *podSpec,
}
在上述代码中,我们通过定义 RequiredDuringSchedulingIgnoredDuringExecution
属性,并设置 NodeSelectorTerms
和 MatchExpressions
来指定 Pod 调度到哪些节点上运行。这里我们要求节点的 zone
标签的值必须是 cn-east-01
或者 cn-east-02
。
需要注意的是,如果指定了多个亲和性规则,则每个规则都必须满足才能将 Pod 调度到对应的节点上。
除了使用 golang 代码进行调度之外,也可以在 Pod 的 YAML 文件中添加相应的 NodeAffinity 字段来指定 Pod 的亲和性调度规则。