獲取執行中容器的 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

在你的 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 卷,容器將該卷掛載到 /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 中,向 nginx 伺服器傳送 GET 請求

# Run this in the shell inside your container
apt-get update
apt-get install curl
curl https:///

輸出顯示你寫入 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-ckubectl exec 命令中指定容器。例如,假設你有一個名為 my-pod 的 Pod,並且該 Pod 有兩個容器,分別名為 *main-app* 和 *helper-app*。以下命令將開啟到 *main-app* 容器的 shell。

kubectl exec -i -t my-pod --container main-app -- /bin/bash

下一步

上次修改時間:2023 年 9 月 19 日太平洋標準時間晚上 11:12: fix: update deprecated command (448734c716)