在 Pod 中的容器之間分享處理程序命名空間

此頁面說明如何為 Pod 設定處理程序命名空間共享。當啟用處理程序命名空間共享時,容器中的處理程序對相同 Pod 中的所有其他容器都可見。

您可以使用此功能來設定協作容器,例如日誌處理常式 Sidecar 容器,或疑難排解不包含 Shell 等偵錯公用程式的容器映像檔。

開始之前

您需要有一個 Kubernetes 叢集,並且必須將 kubectl 命令列工具設定為與您的叢集通訊。建議在至少有兩個節點且未充當控制平面主機的叢集上執行本教學課程。如果您還沒有叢集,可以使用 minikube 建立一個,或者您可以使用以下 Kubernetes playground 之一

設定 Pod

處理程序命名空間共享是使用 Pod 的 .specshareProcessNamespace 欄位啟用的。例如

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
    

    如果您沒有看到命令提示字元,請嘗試按下 Enter 鍵。在容器 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
    

您可以向其他容器中的處理程序發送信號。例如,將 SIGHUP 發送到 nginx 以重新啟動工作處理程序。這需要 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 月 09 日下午 11:18 PST:變更附加到 Shell 容器的命令 (585c1c60c1)