在 Pod 中的容器之間共享程序名稱空間

本頁面展示瞭如何為 Pod 配置程序名稱空間共享。啟用程序名稱空間共享後,一個容器中的程序對同一 Pod 中的所有其他容器可見。

你可以使用此功能來配置協同工作的容器,例如日誌處理 sidecar 容器,或用於除錯不包含 shell 等除錯工具的容器映象。

準備工作

你必須擁有一個 Kubernetes 叢集,並且 kubectl 命令列工具必須配置為與你的叢集通訊。建議在至少有兩個不作為控制平面主機的節點的叢集上執行本教程。如果你還沒有叢集,可以使用 minikube 建立一個,或者使用這些 Kubernetes 遊樂場之一。

配置 Pod

透過 Pod 的 .spec 中的 shareProcessNamespace 欄位啟用程序名稱空間共享。例如:

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  shareProcessNamespace: true
  containers:
  - name: nginx
    image: nginx
  - name: shell
    image: busybox:1.28
    command: ["sleep", "3600"]
    securityContext:
      capabilities:
        add:
        - SYS_PTRACE
    stdin: true
    tty: true
  1. 在你的叢集上建立 Pod nginx

    kubectl apply -f https://k8s.io/examples/pods/share-process-namespace.yaml
    
  2. 連線到 shell 容器並執行 ps

    kubectl exec -it nginx -c shell -- /bin/sh
    

    如果你沒有看到命令列提示符,請嘗試按回車鍵。在容器 shell 中:

    # run this inside the "shell" container
    ps ax
    

    輸出類似於:

    PID   USER     TIME  COMMAND
        1 root      0:00 /pause
        8 root      0:00 nginx: master process nginx -g daemon off;
       14 101       0:00 nginx: worker process
       15 root      0:00 sh
       21 root      0:00 ps ax
    

你可以向其他容器中的程序傳送訊號。例如,向 nginx 傳送 SIGHUP 以重啟工作程序。這需要 SYS_PTRACE 能力。

# run this inside the "shell" container
kill -HUP 8   # change "8" to match the PID of the nginx leader process, if necessary
ps ax

輸出類似於:

PID   USER     TIME  COMMAND
    1 root      0:00 /pause
    8 root      0:00 nginx: master process nginx -g daemon off;
   15 root      0:00 sh
   22 101       0:00 nginx: worker process
   23 root      0:00 ps ax

甚至可以使用 /proc/$pid/root 連結訪問另一個容器的檔案系統。

# run this inside the "shell" container
# change "8" to the PID of the Nginx process, if necessary
head /proc/8/root/etc/nginx/nginx.conf

輸出類似於:

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;

理解程序名稱空間共享

Pod 共享許多資源,因此它們也共享一個程序名稱空間是合理的。然而,一些容器可能期望與其他容器隔離,因此理解其中的差異很重要:

  1. 容器程序不再是 PID 1。某些容器在沒有 PID 1 的情況下拒絕啟動(例如,使用 systemd 的容器),或執行 kill -HUP 1 等命令向容器程序傳送訊號。在共享程序名稱空間的 Pod 中,kill -HUP 1 將向 Pod 沙箱(上述示例中的 /pause)傳送訊號。

  2. 程序對 Pod 中的其他容器可見。這包括 /proc 中可見的所有資訊,例如作為引數或環境變數傳遞的密碼。這些僅受常規 Unix 許可權的保護。

  3. 容器檔案系統透過 /proc/$pid/root 連結對 Pod 中的其他容器可見。這使得除錯更容易,但這也意味著檔案系統秘密僅受檔案系統許可權的保護。

最後修改時間:2024 年 10 月 9 日太平洋標準時間晚上 11:18:更改了連線到 shell 容器的命令 (585c1c60c1)