使用共享卷在同一 Pod 中的容器之間通訊

本頁面展示瞭如何使用卷 (Volume) 在同一 Pod 中執行的兩個容器之間進行通訊。另請參閱如何透過共享程序名稱空間來允許容器之間進行通訊。

準備工作

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

要檢查版本,請輸入 kubectl version

建立執行兩個容器的 Pod

在本練習中,你將建立一個執行兩個容器的 Pod。這兩個容器共享一個卷,它們可以使用該捲進行通訊。這是 Pod 的配置檔案:

apiVersion: v1
kind: Pod
metadata:
  name: two-containers
spec:

  restartPolicy: Never

  volumes:
  - name: shared-data
    emptyDir: {}

  containers:

  - name: nginx-container
    image: nginx
    volumeMounts:
    - name: shared-data
      mountPath: /usr/share/nginx/html

  - name: debian-container
    image: debian
    volumeMounts:
    - name: shared-data
      mountPath: /pod-data
    command: ["/bin/sh"]
    args: ["-c", "echo Hello from the debian container > /pod-data/index.html"]

在配置檔案中,你可以看到 Pod 有一個名為 shared-data 的卷。

配置檔案中列出的第一個容器執行一個 nginx 伺服器。共享卷的掛載路徑是 /usr/share/nginx/html。第二個容器基於 debian 映象,掛載路徑為 /pod-data。第二個容器執行以下命令然後終止。

echo Hello from the debian container > /pod-data/index.html

請注意,第二個容器將 index.html 檔案寫入 nginx 伺服器的根目錄。

建立 Pod 和兩個容器

kubectl apply -f https://k8s.io/examples/pods/two-container-pod.yaml

檢視 Pod 和容器的資訊

kubectl get pod two-containers --output=yaml

以下是部分輸出:

apiVersion: v1
kind: Pod
metadata:
  ...
  name: two-containers
  namespace: default
  ...
spec:
  ...
  containerStatuses:

  - containerID: docker://c1d8abd1 ...
    image: debian
    ...
    lastState:
      terminated:
        ...
    name: debian-container
    ...

  - containerID: docker://96c1ff2c5bb ...
    image: nginx
    ...
    name: nginx-container
    ...
    state:
      running:
    ...

你可以看到 debian 容器已經終止,而 nginx 容器仍在執行。

獲取到 nginx 容器的 shell

kubectl exec -it two-containers -c nginx-container -- /bin/bash

在你的 shell 中,驗證 nginx 是否正在執行

root@two-containers:/# apt-get update
root@two-containers:/# apt-get install curl procps
root@two-containers:/# ps aux

輸出類似於:

USER       PID  ...  STAT START   TIME COMMAND
root         1  ...  Ss   21:12   0:00 nginx: master process nginx -g daemon off;

回想一下,debian 容器在 nginx 根目錄中建立了 index.html 檔案。使用 curl 向 nginx 伺服器傳送 GET 請求

root@two-containers:/# curl localhost

輸出顯示 nginx 提供了一個由 debian 容器編寫的網頁

Hello from the debian container

討論

Pod 可以有多個容器的主要原因是支援輔助應用程式來協助主應用程式。輔助應用程式的典型示例是資料拉取器、資料推送器和代理。輔助應用程式和主應用程式通常需要相互通訊。通常,這透過共享檔案系統(如本練習所示)或透過環回網路介面(localhost)完成。此模式的一個示例是 Web 伺服器以及一個輪詢 Git 儲存庫以獲取新更新的輔助程式。

本練習中的卷提供了一種在 Pod 生命週期內容器之間通訊的方式。如果 Pod 被刪除並重新建立,共享卷中儲存的任何資料都將丟失。

下一步

最後修改於 2023 年 8 月 24 日下午 6:38 PST:使用 code_sample 簡碼代替 code 簡碼 (e8b136c3b3)