节点选择器、亲和性、反亲和性、污点与容忍度
Kubernetes调度器是一个核心组件,负责将Pod分配到合适的节点上。调度器的工作流程包括:
Pod创建 → 过滤节点 → 节点打分 → 选择节点 → 绑定Pod
作用:通过标签选择器将Pod调度到具有特定标签的节点上。
使用场景:简单的节点选择需求,如将Pod调度到特定硬件类型的节点上。
apiVersion: v1
kind: Pod
metadata:
name: node-selector-demo
spec:
containers:
- name: nginx
image: nginx:1.21
nodeSelector:
kubernetes.io/os: linux
type: worker
作用:比节点选择器更灵活的节点选择机制,支持更复杂的规则。
类型:
apiVersion: v1
kind: Pod
metadata:
name: node-affinity-demo
spec:
containers:
- name: nginx
image: nginx:1.21
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/os
operator: In
values:
- linux
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 1
preference:
matchExpressions:
- key: type
operator: In
values:
- worker
作用:将相关的Pod调度到同一位置(同一节点、可用区或区域)。
使用场景:提高服务间通信性能,如将前端和后端Pod调度到同一节点。
作用:将Pod分散到不同的位置,提高可用性和容错能力。
使用场景:高可用性部署,如将同一应用的多个副本调度到不同节点。
apiVersion: apps/v1
kind: Deployment
metadata:
name: pod-affinity-demo
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.21
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- nginx
topologyKey: kubernetes.io/hostname
污点:应用于节点上的标记,表示该节点不希望接收某些Pod。
容忍度:应用于Pod上的标记,表示该Pod可以容忍节点上的污点。
# 给节点添加污点
kubectl taint nodes node1 key=value:NoSchedule
# Pod配置容忍度
apiVersion: v1
kind: Pod
metadata:
name: toleration-demo
spec:
containers:
- name: nginx
image: nginx:1.21
tolerations:
- key: "key"
operator: "Equal"
value: "value"
effect: "NoSchedule"
tolerationSeconds: 3600
# 查看节点标签
kubectl get nodes --show-labels
# 给节点添加标签
kubectl label nodes node1 type=worker
# 查看节点污点
kubectl describe node node1 | grep Taints
# 给节点添加污点
kubectl taint nodes node1 key=value:NoSchedule
# 移除节点污点
kubectl taint nodes node1 key:NoSchedule-
# 查看Pod的调度情况
kubectl get pods -o wide
kubectl describe pod <pod-name> | grep Node:
可能原因:没有满足调度规则的节点
解决方案:检查节点标签、污点设置,调整调度规则
可能原因:调度规则设置不当
解决方案:调整亲和性规则或污点设置
可能原因:节点标签不正确或规则设置错误
解决方案:检查节点标签和亲和性规则配置
调度策略是Kubernetes中非常重要的概念,通过合理配置调度策略,可以:
在实际应用中,需要根据应用的特性和需求,选择合适的调度策略,以达到最佳的部署效果。调度策略的选择应该考虑应用的性能要求、可用性需求、资源需求等因素。