跳到主要内容

k8s调度器相关

1.调度器Scheduler 概念

Scheduler 是 kubernetes 的调度器,主要任务是把 Pod 分配到集群的节点上。Scheduler 作为单独的程序运行,启动后持续监听 API Server,获取 PodSpec.NodeName 为空的 Pod,为每个 Pod 创建 binding。

image-20250512235501149

预选过程

  • PodFitsResources:节点剩余资源是否满足 Pod 请求
  • PodFitsHost:检查 NodeName 是否匹配
  • PodFitsHostPorts:检查端口冲突
  • PodSelectorMatches:过滤不匹配 label 的节点
  • NoDiskConflict:检查 volume 冲突

优选过程

  • LeastRequestedPriority:资源使用率越低权重越高
  • BalancedResourceAllocation:CPU 和 Memory 使用率越接近权重越高
  • ImageLocalityPriority:倾向于已有目标镜像的节点

使用自定义调度器

# 启动 API Server 代理
kubectl proxy --port=8001

# 创建使用自定义调度器的 Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: myapp
name: myapp
spec:
replicas: 1
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
schedulerName: my-scheduler
containers:
- image: wangyanglinux/myapp:v1.0
name: myapp

2.亲和性

Node 亲和性

  • requiredDuringSchedulingIgnoredDuringExecution:硬策略,必须满足
  • preferredDuringSchedulingIgnoredDuringExecution:软策略,尽量满足

Pod 亲和性/反亲和性

  • Pod 亲和性:将 Pod 调度到有特定 Pod 的节点上
  • Pod 反亲和性:避免将 Pod 调度到有特定 Pod 的节点上

3.容忍(Toleration)与污点(Taint)

Taint 标记节点,只有设置了对应 Toleration 的 Pod 才能调度到该节点上。

污点 effect 类型:

  • NoSchedule:不调度到该节点
  • PreferNoSchedule:尽量不调度
  • NoExecute:不调度且驱逐已有 Pod
# 设置污点
kubectl taint nodes node1 key1=value1:NoSchedule

# 去除污点
kubectl taint nodes node1 key1:NoSchedule-

# Pod 设置容忍
tolerations:
- key: "key1"
operator: "Equal"
value: "value1"
effect: "NoSchedule"

4.固定节点调度

指定节点(nodeName)

跳过 Scheduler,强制调度到指定节点。

spec:
nodeName: k8s-node01

指定节点标签(nodeSelector)

通过 label-selector 匹配节点,由 Scheduler 调度。

spec:
nodeSelector:
type: nodeselect