Kubernetes Pod调度之nodeSelector与亲和性
一、nodeSelector:基于节点标签调度
作用:把 Pod 调度到带有指定标签的节点上,属于硬限制。
1. 给节点打标签
kubectl get nodes --show-labels
kubectl label nodes --all school=demo
kubectl label nodes worker232 school- # 删除 worker232 的 school 标签
kubectl get nodes -l school=demo --show-labels
2. 使用 nodeSelector
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: scheduler-nodeselector
spec:
selector:
matchLabels:
apps: xiuxian
template:
metadata:
labels:
apps: xiuxian
spec:
tolerations:
- key: node-role.kubernetes.io/master
effect: NoSchedule
nodeSelector:
school: demo
containers:
- name: xiuxian
image: registry.cn-hangzhou.aliyuncs.com/demo-k8s/apps:v1
DaemonSet 只会落到 school=demo 的节点上。
二、nodeAffinity:基于节点标签的亲和性
作用同 nodeSelector,但扩展性更强:支持同一个 key 的多个 value、支持软限制。简言之,nodeSelector 能做的 nodeAffinity 都能做,反过来不一定。
1. 硬限制(required)
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: school
values:
- "demo"
operator: In
containers:
- name: xiuxian
image: registry.cn-hangzhou.aliyuncs.com/demo-k8s/apps:v1
operator 取值:
| 操作符 | 含义 |
|---|---|
| In | key 的值在 values 列表中(白名单) |
| NotIn | 与 In 相反(黑名单) |
| Exists | 只要 key 存在,values 可省略 |
| DoesNotExist | 与 Exists 相反 |
| Gt | 大于,value 必须是数字字符串 |
| Lt | 小于,value 必须是数字字符串 |
2. 多值匹配
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: school
values:
- "demo"
- "demo2"
operator: In
三、硬限制与软限制的区别
| 类型 | 字段 | 行为 |
|---|---|---|
| 硬限制 | requiredDuringSchedulingIgnoredDuringExecution | 条件不匹配就始终不调度 |
| 软限制 | preferredDuringSchedulingIgnoredDuringExecution | 尽量按条件调度,不匹配也可调度到其他节点 |
nodeSelector 只有硬限制;nodeAffinity 两者都支持。生产环境对「一定要调度成功」的场景可用软限制。
软限制示例
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- preference:
matchExpressions:
- key: school
values:
- "demo"
operator: In
weight: 50
- preference:
matchExpressions:
- key: school
values:
- "demo2"
operator: In
weight: 80
containers:
- name: c1
image: registry.cn-hangzhou.aliyuncs.com/demo-k8s/apps:v2
weight 是权重,有效值 1–100,值越大优先级越高。
四、Pod 亲和性与反亲和性
- Pod 亲和性(podAffinity):假设有 3 个数据中心,一个 Pod 调度到某数据中心后,后续 Pod 尽量也往同一数据中心调度;
- Pod 反亲和性(podAntiAffinity):与亲和性相反,后续 Pod 尽量不往该数据中心调度。
五、podAffinity
先给节点打「数据中心」标签:
kubectl label nodes master231 dc=dc1
kubectl label nodes worker232 dc=dc2
kubectl label nodes worker233 dc=dc3
kubectl get nodes --show-labels -l dc
Pod 亲和性资源清单(课堂记录到这里中断,以下为节选开头):
apiVersion: apps/v1
kind: Deployment
metadata:
name: scheduler-podaffinity
spec:
replicas: 5
selector:
matchLabels:
apps: xiuxian