k8s pod之间不能通信_Kubernetes 同 Pod 内的容器使用共享卷通信
本文旨在說明如何讓一個 Pod 內的兩個容器使用一個卷(Volume)進行通信。
Before you begin
You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. If you do not already have a cluster, you can create one by using?Minikube.
創建一個包含兩個容器的 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
注意,第二個容器在 nginx 服務器的根目錄下寫了?index.html?文件。
創建一個包含兩個容器的 Pod:
kubectl create -f https://k8s.io/docs/tasks/access-application-cluster/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:/# 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:/# apt-get update
root@two-containers:/# apt-get install curl
root@two-containers:/# curl localhost
輸出表示 nginx 提供了 debian 容器寫的頁面:
Hello from the debian container
討論
Pod 能有多個容器的主要原因是為了支持輔助應用(helper applications),以協助主應用(primary application)。 輔助應用的典型例子是數據抽取,數據推送和代理。輔助應用和主應用經常需要相互通信。 就如這個練習所示,通信通常是通過共享文件系統完成的,或者,也通過回環網絡接口 localhost 完成。 舉個網絡接口的例子,web 服務器帶有一個協助程序用于拉取 Git 倉庫的更新。
在本練習中的卷為 Pod 生命周期中的容器相互通信提供了一種方法。如果 Pod 被刪除或者重建了, 任何共享卷中的數據都會丟失。
What’s next
總結
以上是生活随笔為你收集整理的k8s pod之间不能通信_Kubernetes 同 Pod 内的容器使用共享卷通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: callback用法 js vue_Vu
- 下一篇: python爬虫经典段子_Python爬