取得執行中容器的 Shell
此頁面說明如何使用 kubectl exec
取得執行中容器的 Shell。
事前準備
您需要有一個 Kubernetes 叢集,而且必須將 kubectl 命令列工具設定為與您的叢集通訊。建議在至少有兩個節點且未充當控制平面主機的叢集上執行本教學課程。如果您還沒有叢集,可以使用 minikube 建立一個,或者您可以使用下列 Kubernetes 體驗環境之一
取得容器的 Shell
在本練習中,您建立一個具有一個容器的 Pod。容器執行 nginx 映像檔。以下是 Pod 的組態檔
apiVersion: v1
kind: Pod
metadata:
name: shell-demo
spec:
volumes:
- name: shared-data
emptyDir: {}
containers:
- name: nginx
image: nginx
volumeMounts:
- name: shared-data
mountPath: /usr/share/nginx/html
hostNetwork: true
dnsPolicy: Default
建立 Pod
kubectl apply -f https://k8s.io/examples/application/shell-demo.yaml
驗證容器是否正在執行
kubectl get pod shell-demo
取得執行中容器的 Shell
kubectl exec --stdin --tty shell-demo -- /bin/bash
注意
雙破折號 (--
) 分隔您想要傳遞至命令的引數與 kubectl 引數。在您的 Shell 中,列出根目錄
# Run this inside the container
ls /
在您的 Shell 中,實驗其他命令。以下是一些範例
# You can run these example commands inside the container
ls /
cat /proc/mounts
cat /proc/1/maps
apt-get update
apt-get install -y tcpdump
tcpdump
apt-get install -y lsof
lsof
apt-get install -y procps
ps aux
ps aux | grep nginx
撰寫 nginx 的根頁面
再次查看您的 Pod 的組態檔。Pod 具有 emptyDir
Volume,而容器將 Volume 掛載在 /usr/share/nginx/html
。
在您的 Shell 中,在 /usr/share/nginx/html
目錄中建立 index.html
檔案
# Run this inside the container
echo 'Hello shell demo' > /usr/share/nginx/html/index.html
在您的 Shell 中,將 GET 請求傳送至 nginx 伺服器
# Run this in the shell inside your container
apt-get update
apt-get install curl
curl https://127.0.0.1/
輸出顯示您寫入 index.html
檔案的文字
Hello shell demo
當您完成 Shell 時,輸入 exit
。
exit # To quit the shell in the container
在容器中執行個別命令
在一般命令視窗 (而非您的 Shell) 中,列出執行中容器中的環境變數
kubectl exec shell-demo -- env
實驗執行其他命令。以下是一些範例
kubectl exec shell-demo -- ps aux
kubectl exec shell-demo -- ls /
kubectl exec shell-demo -- cat /proc/1/mounts
當 Pod 有多個容器時開啟 Shell
如果 Pod 有多個容器,請使用 --container
或 -c
在 kubectl exec
命令中指定容器。例如,假設您有一個名為 my-pod 的 Pod,而該 Pod 有兩個名為 *main-app* 和 *helper-app* 的容器。下列命令會開啟 *main-app* 容器的 Shell。
kubectl exec -i -t my-pod --container main-app -- /bin/bash
注意
簡短選項-i
和 -t
與長選項 --stdin
和 --tty
相同下一步
- 閱讀關於 kubectl exec 的資訊
上次修改時間為 2023 年 9 月 19 日下午 11:12 PST:fix: update deprecated command (448734c716)