获取运行中容器的 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)