構建基本的 DaemonSet

本頁面演示如何構建一個基本的 DaemonSet,使其在 Kubernetes 叢集的每個節點上執行一個 Pod。它涵蓋了一個簡單的用例,即從主機掛載檔案,使用 init 容器記錄其內容,並利用一個暫停容器。

準備工作

你需要一個 Kubernetes 叢集,並且 kubectl 命令列工具已配置為與你的叢集通訊。建議在至少有兩個不作為控制平面主機的節點叢集上執行本教程。如果你還沒有叢集,可以使用 minikube 建立一個,或者使用這些 Kubernetes 遊樂場之一。

一個至少包含兩個節點(一個控制平面節點和一個工作節點)的 Kubernetes 叢集,以演示 DaemonSet 的行為。

定義 DaemonSet

在此任務中,建立了一個基本的 DaemonSet,它確保 Pod 的副本被排程到每個節點上。該 Pod 將使用一個 init 容器讀取並記錄主機上的 /etc/machine-id 檔案的內容,而主容器將是一個 pause 容器,它保持 Pod 執行。

apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: example-daemonset
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: example
  template:
    metadata:
      labels:
        app.kubernetes.io/name: example
    spec:
      containers:
      - name: pause
        image: registry.k8s.io/pause
      initContainers:
      - name: log-machine-id
        image: busybox:1.37
        command: ['sh', '-c', 'cat /etc/machine-id > /var/log/machine-id.log']
        volumeMounts:
        - name: machine-id
          mountPath: /etc/machine-id
          readOnly: true
        - name: log-dir
          mountPath: /var/log
      volumes:
      - name: machine-id
        hostPath:
          path: /etc/machine-id
          type: File
      - name: log-dir
        hostPath:
          path: /var/log
  1. 基於 (YAML) 清單建立 DaemonSet

    kubectl apply -f https://k8s.io/examples/application/basic-daemonset.yaml
    
  2. 應用後,你可以驗證 DaemonSet 是否在叢集的每個節點上執行一個 Pod。

    kubectl get pods -o wide
    

    輸出將列出每個節點一個 Pod,類似於

    NAME                                READY   STATUS    RESTARTS   AGE    IP       NODE
    example-daemonset-xxxxx             1/1     Running   0          5m     x.x.x.x  node-1
    example-daemonset-yyyyy             1/1     Running   0          5m     x.x.x.x  node-2
    
  3. 你可以透過檢查從主機掛載的日誌目錄來檢查已記錄的 /etc/machine-id 檔案的內容

    kubectl exec <pod-name> -- cat /var/log/machine-id.log
    

    其中 <pod-name> 是你的一個 Pod 的名稱。

清理

要刪除 DaemonSet,請執行以下命令

kubectl delete --cascade=foreground --ignore-not-found --now daemonsets/example-daemonset

這個簡單的 DaemonSet 示例介紹了 init 容器和主機路徑卷等關鍵元件,這些元件可以在更高階的用例中進行擴充套件。更多詳情請參考 DaemonSet

下一步

上次修改時間:2025 年 1 月 7 日太平洋標準時間上午 9:41:清理 create-daemon-set.md (3407a0e1cd)