k8s pod之间不能通信_Kubernetes 同 Pod 内的容器使用共享卷通信
本文旨在說明如何讓一個(gè) Pod 內(nèi)的兩個(gè)容器使用一個(gè)卷(Volume)進(jìn)行通信。
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.
創(chuàng)建一個(gè)包含兩個(gè)容器的 Pod
在這個(gè)練習(xí)中,你會(huì)創(chuàng)建一個(gè)包含兩個(gè)容器的 Pod。兩個(gè)容器共享一個(gè)卷用于他們之間的通信。 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 有一個(gè)共享卷,名為?shared-data。
配置文件中的第一個(gè)容器運(yùn)行了一個(gè) nginx 服務(wù)器。共享卷的掛載路徑是?/usr/share/nginx/html。 第二個(gè)容器是基于 debian 鏡像的,有一個(gè)?/pod-data?的掛載路徑。第二個(gè)容器運(yùn)行了下面的命令然后終止。
echo Hello from the debian container > /pod-data/index.html
注意,第二個(gè)容器在 nginx 服務(wù)器的根目錄下寫了?index.html?文件。
創(chuàng)建一個(gè)包含兩個(gè)容器的 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 容器已經(jīng)被終止了,而 nginx 服務(wù)器依然在運(yùn)行。
進(jìn)入 nginx 容器的 shell:
kubectl exec -it two-containers -c nginx-container -- /bin/bash
在 shell 中,確認(rèn) nginx 還在運(yùn)行。
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 的根目錄下創(chuàng)建了?index.html?文件。 使用?curl?向 nginx 服務(wù)器發(fā)送一個(gè) GET 請(qǐng)求:
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 能有多個(gè)容器的主要原因是為了支持輔助應(yīng)用(helper applications),以協(xié)助主應(yīng)用(primary application)。 輔助應(yīng)用的典型例子是數(shù)據(jù)抽取,數(shù)據(jù)推送和代理。輔助應(yīng)用和主應(yīng)用經(jīng)常需要相互通信。 就如這個(gè)練習(xí)所示,通信通常是通過共享文件系統(tǒng)完成的,或者,也通過回環(huán)網(wǎng)絡(luò)接口 localhost 完成。 舉個(gè)網(wǎng)絡(luò)接口的例子,web 服務(wù)器帶有一個(gè)協(xié)助程序用于拉取 Git 倉庫的更新。
在本練習(xí)中的卷為 Pod 生命周期中的容器相互通信提供了一種方法。如果 Pod 被刪除或者重建了, 任何共享卷中的數(shù)據(jù)都會(huì)丟失。
What’s next
總結(jié)
以上是生活随笔為你收集整理的k8s pod之间不能通信_Kubernetes 同 Pod 内的容器使用共享卷通信的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: callback用法 js vue_Vu
- 下一篇: java生成数据插入hbase_hbas