iT邦幫忙

2021 iThome 鐵人賽

DAY 30
4
DevOps

k8s 入門學習 30天系列 第 30

IT 鐵人賽 k8s 入門30天 -- day30 Share Process Namespace between Containers in a Pod

參考文件 https://kubernetes.io/docs/tasks/configure-pod-container/share-process-namespace/

前言

今天要來實作 Share Process Namespace between Containers in a Pod 這個任務

在同一個 Pod 的 Container 內的 Process 可以透過 namespace sharing 的方式, 讓彼此可以互相溝通

這種設定可以用來讓同一個 Pod 內的 Container 彼此合作. 舉例來說, 建立一個專門處理應用log 的 SideCar Container 或是建立一個用來 Debug 的 Container 就可以這樣做

佈署目標

1 建立一個 Pod 設定 shareProcessNames 讓 Container 間 Process 可以互通

2 透過連線到其中一的 Container 驗證查看另一個 Container 的 Process

建立一個 Pod 設定 shareProcessNames 讓 Container 間 Process 可以互通

建立 share-process-namespace.yaml 如下:

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  shareProcessNamespace: true
  containers:
  - name: nginx
    image: nginx
  - name: shell
    image: busybox
    securityContext:
      capabilities:
        add:
        - SYS_PTRACE
    stdin: true
    tty: true

建立一個 Pod

名稱設定為 nginx

設定 shareProcessNamespace 為 true 這個設定用來讓 Containers 間的 Process 可以互通

設定第一個 Container 使用 image 為 nginx 名稱設定為 nginx

設定第二個 Container 使用 image 為 busybox 名稱設定為 shell

設定第二個 Container 設定 securityContext 如下

capabilities:
  add:
  - SYS_PTRACE

增加這個 SYS_PTRACE 是開啟 可以讓另一個 Container Process 操作這個 busybox Container process 的權限

設定第二個 Container 開啟 tty: true, stdin: true 打開 terminal 與 stdin 權限

建立佈署使用以下指令

kubectl apply -f share-process-namespace.yaml

透過連線到其中一的 Container 驗證查看另一個 Container 的 Process

透過以下指令連線到 nginx

kubectl attach -it nginx -c shell

使用以下指令查看 Process

ps ax

透過以下指令發 SIGNUP 到 nginx 來重新啟動 worker process

kill -HUP 7

注意的是, 這邊 7 這個 PID 可能因為每個佈署的不同而不同, 需要透過上面 ps ax 找到 master process 來處理

然後使用以下指令驗證一下重起狀態

ps ax

使用以下指令來查看 /proc/$pid/root 連結

head /proc/7/root/etc/nginx/nginx.conf

其他

同一個 Pod 的 Container 透過 shared namespace namespace

以下有幾個特性

  1. Container process 將不再有 PID 1

有些 Container 需要 PID 1 來開啟比如說需要 systemd 的 image

會透過 kill -HUP 1 來重啟 Container Process

在 Pod 有開啟 share process namespace, kill -HUP 1 則會變成發指令到 Pod 的 sandbox

  1. 在同一個 Pod 的 Process 彼此都可以看見

包括所有在 /proc 下的資訊, 比如說環境參數或是運行參數

可是存取仍然需要是具有對應 UNIX 權限的使用者

  1. 可以透過 /proc/$pid/root 來看到其他在同一個 Pod 的 Container 的檔案系統

透過這個方式可以有效的做 debug

後記

這篇是 k8s 入門 30 天的最後一篇

大致上介紹了一些基礎 k8s 基礎概念

筆者發現在研究時由於自身經驗的不足, 常常無法用良好的實際案例來解說

想要更理解 k8s 的效用, 後續應該要做更延伸應用

還需要去研究許多比如資訊安全的設置, NAT, Metric 監測, 或是建制 ci/cd 的 Pipeline runner 等等也許都是不錯的應用情境

感謝各位訂閱者一直以來的觀看筆者的文章


上一篇
IT 鐵人賽 k8s 入門30天 -- day29 Adding entries to Pod /etc/hosts with HostAliases
系列文
k8s 入門學習 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
雷N
iT邦研究生 1 級 ‧ 2021-10-14 12:48:16

賀 完賽
期待下午茶聚會 /images/emoticon/emoticon31.gif

json_liang iT邦研究生 5 級 ‧ 2021-10-14 13:46:34 檢舉

/images/emoticon/emoticon08.gif

0
Mandy
iT邦新手 3 級 ‧ 2021-10-15 03:50:06

賀!完賽

我要留言

立即登入留言