iT邦幫忙

2021 iThome 鐵人賽

DAY 27
2
DevOps

k8s 入門學習 30天系列 第 27

IT 鐵人賽 k8s 入門30天 -- day27 Communicate Between Containers in the Same Pod Using a Shared Volume

前言

今天要來實作 Communicate Between Containers in the Same Pod Using a Shared Volume 這個任務

k8s 在一個 Pod 內可以跑多個 container

而一般來說 Pod 會有一個主要應用的 container , 其他則是輔助應用的 container

這些 container 可以透過掛載 Pod 內的同一個 Volume 來做溝通

這次這個任務就是要來實踐上面所說

建立兩個 Container , nginx 與 debian , 共同掛載同一個 Volume

debian 把資料寫入 shared-data 內

nginx 再從 shared-data 把檔案牘出來

佈署目標

1 建立一個包含兩個 container 的 Pod

2 進入 nginx 的 container 驗證可以從 shared-data 讀出 debian 寫入的檔

3 清除佈署

建立一個包含兩個 container 的 Pod

建立 two-container-pod.yaml 如下:

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

名稱設定為 two-containers

設定 volumes 名稱為 shared-data

設定 container nginx-container 的 image 為 nginx

設定 container nginx-container 掛載 volume shared-data 到 /usr/share/nginx/html

設定 container debian 的 image 為 debian

設定 container debian 掛載 volume shared-data 到 /pod-data

設定 container debian 執行指令如下

/bin/sh -c "echo Hello from the debian container" > /pod-data/index.html

建立佈署指令如下:

kubectl apply -f two-container-pod.yaml

檢查佈署指令如下:

kubectl get pod two-containers --output=yaml

進入 nginx 的 container 驗證可以從 shared-data 讀出 debian 寫入的檔

進入 nginx-container 指令如下:

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

在 nginx-container terminal 執行指令如下:

apt-get update
apt-get install curl procps
ps aux

執行驗證指令如下:

curl localhost

清除佈署

kubectl delete -f two-container-pod.yaml

後記

這個範例任務中, 兩個在同一個 Pod 的兩個 container 透過 Pod 的 Volumes 來做溝通

然而, 假設 Pod 被刪除並且重新建立, 任何建立在 Volume 內的資料都會消失

所以並非是個好方法, 溝通方式還是應該用透過 api 或是 message queue 的方式才比較即時


上一篇
IT 鐵人賽 k8s 入門30天 day26 k8s Task Set up Ingress on Minikube with the NGINX Ingress Controller
下一篇
IT 鐵人賽 k8s 入門30天 -- day28 k8s Service Catalog
系列文
k8s 入門學習 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言