Node taints 和 tolerations 是 Kubernetes 中用于控制和影响 pod 调度到节点上的机制。它们帮助确保某些 pod 仅调度到特定节点,或者防止 pod 调度到不适合它们的节点。
### **Node Taints**
**taint** 是应用于节点的一种属性,用于标记节点具有特殊条件或限制。taints 允许节点排斥那些没有显式容忍该 taint 的 pod。这在需要为特定工作负载保留某些节点或防止某些 pod 调度到具有特定特征的节点时非常有用。
每个 taint 包含三个组件:
1. **Key**: 标识 taint 的字符串。
2. **Value**: 与 key 关联的可选字符串。
3. **Effect**: 指定 taint 的行为,可以是以下之一:
- `NoSchedule`: 不容忍该 taint 的 pod 将不会调度到该节点。
- `PreferNoSchedule`: Kubernetes 会尝试避免调度不容忍该 taint 的 pod,但不保证。
- `NoExecute`: 不容忍该 taint 的 pod 如果已经运行,将会从节点上驱逐,同时新的 pod 也不会调度到该节点。
向节点添加 taint 的示例:
```bash
kubectl taint nodes <node-name> key=value:NoSchedule
```
### **Tolerations**
**toleration** 是应用于 pod 的一种属性,允许 pod "容忍" 节点的 taint。如果 pod 具有与节点 taint 匹配的 toleration,则该 pod 可以调度到该节点,即使节点有 taint。
每个 toleration 包含以下组件:
1. **Key**: pod 容忍的 taint 的 key。
2. **Value**: pod 容忍的 taint 的 value。
3. **Effect**: pod 容忍的 taint 的 effect (`NoSchedule`, `PreferNoSchedule`, 或 `NoExecute`)。
4. **Operator**: 指定 key 和 value 之间的关系,可以是:
- `Equal`: 如果 key 和 value 相等,则 toleration 匹配 taint。
- `Exists`: 如果 key 存在,则 toleration 匹配 taint,无论 value 是什么。
向 pod 添加 toleration 的示例:
```yaml
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
tolerations:
- key: "key"
operator: "Equal"
value: "value"
effect: "NoSchedule"
```
### **Taints 和 Tolerations 如何协同工作**
- Taints 应用于节点,用于指示某些 pod 不应调度到该节点,除非它们显式容忍该 taint。
- Tolerations 应用于 pod,用于指示它们可以调度到具有匹配 taint 的节点。
如果节点有 taint,而 pod 没有匹配的 toleration,则该 pod 将不会调度到该节点。
### **使用场景**
1. **专用节点**: 通过向节点应用 taint 并向相应的 pod 添加 toleration,为特定工作负载保留节点。
2. **节点维护**: 通过应用 taint 暂时阻止 pod 调度到节点。
3. **特殊硬件**: 确保需要特定硬件(例如 GPU)的 pod 仅调度到具有该硬件的节点。
### **检查 Taints 和 Tolerations**
为了确保 taints 和 tolerations 不会阻止 pod 调度:
1. **检查节点的 taints**:
```bash
kubectl describe nodes <node-name>
```
在节点描述中查找 `Taints` 部分。
2. **检查 pod 的 tolerations**:
```bash
kubectl describe pod <pod-name>
```
在 pod 描述中查找 `Tolerations` 部分。
3. 确保节点上的 taints 与需要调度到这些节点的 pod 的 tolerations 匹配。如果不匹配,pod 可能无法调度。
通过正确配置 taints 和 tolerations,可以控制 pod 的放置,并确保 Kubernetes 集群中的资源高效利用。