02 - Taints and Tolerations

摘要

Taints Tolerations 是 Kubernetes 中用來 控制 Pod 調度到哪些節點 的機制。

[K8s] Taints and Tolerations

✅ Taints 設定在節點上,防止 Pod 調度到該節點

✅ Tolerations 設定在 Pod 上,使其能夠忽略某些 Taints

✅ 透過 NoSchedule、PreferNoSchedule、NoExecute 來控制 Pod 的行為

✅ 控制特定 Pod 運行在特定節點,提升調度靈活性

這個機制在 Kubernetes 多節點部署資源隔離避免影響關鍵應用 時非常有用 🚀


Taints(污點)

Taint 是設定在 節點 (Node) 上的屬性,它告訴 Kubernetes 不要在該節點上調度沒有相應 Toleration(容忍度)的 Pod。

$ kubectl taint node <node-name> <key>=<value>:<effect>   

  • <node-name> → 要添加 taint 的節點名稱
  • <effect> → taint 的影響方式
    • NoSchedule → 禁止 沒有匹配 Toleration 的 Pod 被調度到該節點
    • PreferNoSchedule → 盡量避免 調度,但不是強制的
    • NoExecute → 不僅禁止調度,還會驅逐 已經在該節點上的不符合 Toleration 的 Pod


Tolerations(容忍度)

Toleration 設定在 Pod 上,允許 Pod 忽略某些 Taint(污點),從而能夠被調度到相應的節點。

在 Pod 規範 (pod.yaml) 中添加 tolerations:

```
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  tolerations:
    - key: "dedicated"
      operator: "Equal"
      value: "special"
      effect: "NoSchedule"
  containers:
    - name: nginx
      image: nginx
```
✅ 這個 Pod 允許被調度到有 dedicated=special:NoSchedule taint 的節點 node1。
🚫 但其他沒有該 Toleration 的 Pod 仍然無法被調度。


移除 Taint(污點)

刪除一個節點上的 Taint

$ kubectl taint nodes [NODE_NAME] [KEY]=[VALUE]:[EFFECT]-       

驗證 Taint 是否已移除

$ kubectl describe node [NODE_NAME] | grep Taint                           
如果輸出為 <none>,表示 taint 已成功移除。


Q: Do any taints exist on `node01` node?

$ kubectl describe node node01 | grep -i taints                       


Q: Create a taint on `node01` with key of `spray`, value of `mortein` and effect of `NoSchedule`

$ kubectl taint --help                                                     

$ kubectl taint node node01 spray=mortein:NoSchedule      

讓 node01 只允許特定 Pod (擁有 key:spray, value:mortein 的 Pod) 被調度


Q: 如圖所示

原因:Pod Mosquito can not tolerate taint Mortein.

Q: Create another pod named `bee` with the `nginx` image, which has a toleration set to the taint `mortein`.

  • Image name: nginx
  • Key: spray
  • Value: mortein
  • Effect: NoSchedule
  • Status: Running

$ kubectl run bee --image=nginx --dry-run=client -o yaml > bee.yaml       

$ kubectl create -f bee.yaml                                                                   

$ kubectl get pods --watch                                                                    

```
apiVersion: v1
kind: Pod
metadata:
  name: bee
spec:
  containers:
  - image: nginx
    name: bee
  tolerations:
  - key: spray
    value: mortein
    effect: NoSchedule
    operator: Equal

```


Q: 得知 Pod 被安排在哪個 Node 上

$ kubectl get pods -o wide                    




Q: Remove the taint on `controlplane`, which currently has the taint effect of `NoSchedule`.

$ kubectl describe node controlplane                                            

$ kubectl taint nodes controlplane node-role.kubernetes.io/control-plane:NoSchedule-   

如果輸出為 <none>,表示 taint 已成功移除。



留言