在同一個 Pod 中的容器之間使用共享卷進行通訊
本頁說明如何在同一個 Pod 中執行的兩個 Container 之間使用 Volume 進行通訊。另請參閱如何透過在 Container 之間共用程序命名空間來允許程序進行通訊。
準備開始
您需要有一個 Kubernetes 叢集,並且必須設定 kubectl 命令列工具以與您的叢集通訊。建議在至少有兩個節點且未充當控制平面主機的叢集上執行本教學課程。如果您還沒有叢集,可以使用 minikube 建立一個,或者您可以使用以下 Kubernetes 練習場之一
若要檢查版本,請輸入kubectl version
。建立執行兩個 Container 的 Pod
在本練習中,您將建立一個執行兩個 Container 的 Pod。這兩個 Container 共用一個 Volume,它們可以使用該 Volume 進行通訊。以下是 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
的 Volume。
組態檔中列出的第一個 Container 執行 nginx 伺服器。共用 Volume 的掛載路徑是 /usr/share/nginx/html
。第二個 Container 以 debian 映像檔為基礎,掛載路徑為 /pod-data
。第二個 Container 執行以下命令,然後終止。
echo Hello from the debian container > /pod-data/index.html
請注意,第二個 Container 在 nginx 伺服器的根目錄中寫入 index.html
檔案。
建立 Pod 和兩個 Container
kubectl apply -f https://k8s.io/examples/pods/two-container-pod.yaml
檢視關於 Pod 和 Container 的資訊
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 Container 已終止,而 nginx Container 仍在執行。
取得 nginx Container 的 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 Container 在 nginx 根目錄中建立了 index.html
檔案。使用 curl
將 GET 請求傳送至 nginx 伺服器
root@two-containers:/# curl localhost
輸出顯示 nginx 伺服由 debian Container 寫入的網頁
Hello from the debian container
討論
Pod 可以有多個 Container 的主要原因是為了支援協助主要應用程式的輔助應用程式。輔助應用程式的典型範例是資料提取器、資料推送器和 Proxy。輔助應用程式和主要應用程式通常需要彼此通訊。通常,這是透過共用檔案系統(如本練習所示)或透過迴路網路介面 localhost 完成的。此模式的一個範例是 Web 伺服器以及輪詢 Git 儲存庫以取得新更新的輔助程式。
本練習中的 Volume 提供了一種讓 Container 在 Pod 的生命週期內進行通訊的方式。如果 Pod 被刪除並重新建立,則儲存在共用 Volume 中的任何資料都將遺失。