获取运行中容器的 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 http://localhost/

输出显示你写入 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-apphelper-app。以下命令将打开 main-app 容器的 Shell。

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

接下来

最后修改于 2023 年 9 月 19 日晚上 11:12 PST: fix: update deprecated command (448734c716)