在 Pod 中的容器之間共享程序名稱空間
本頁面展示瞭如何為 Pod 配置程序名稱空間共享。啟用程序名稱空間共享後,一個容器中的程序對同一 Pod 中的所有其他容器可見。
你可以使用此功能來配置協同工作的容器,例如日誌處理 sidecar 容器,或用於除錯不包含 shell 等除錯工具的容器映象。
準備工作
你必須擁有一個 Kubernetes 叢集,並且 kubectl 命令列工具必須配置為與你的叢集通訊。建議在至少有兩個不作為控制平面主機的節點的叢集上執行本教程。如果你還沒有叢集,可以使用 minikube 建立一個,或者使用這些 Kubernetes 遊樂場之一。
配置 Pod
透過 Pod 的 .spec
中的 shareProcessNamespace
欄位啟用程序名稱空間共享。例如:
在你的叢集上建立 Pod
nginx
kubectl apply -f https://k8s.io/examples/pods/share-process-namespace.yaml
連線到
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 共享許多資源,因此它們也共享一個程序名稱空間是合理的。然而,一些容器可能期望與其他容器隔離,因此理解其中的差異很重要:
容器程序不再是 PID 1。某些容器在沒有 PID 1 的情況下拒絕啟動(例如,使用
systemd
的容器),或執行kill -HUP 1
等命令向容器程序傳送訊號。在共享程序名稱空間的 Pod 中,kill -HUP 1
將向 Pod 沙箱(上述示例中的/pause
)傳送訊號。程序對 Pod 中的其他容器可見。這包括
/proc
中可見的所有資訊,例如作為引數或環境變數傳遞的密碼。這些僅受常規 Unix 許可權的保護。容器檔案系統透過
/proc/$pid/root
連結對 Pod 中的其他容器可見。這使得除錯更容易,但這也意味著檔案系統秘密僅受檔案系統許可權的保護。