4.9 KiB
reviewers | title | content_template | ||
---|---|---|---|---|
|
获取正在运行容器的 Shell | templates/task |
{{% capture overview %}}
本文介绍怎样使用 kubectl exec
命令获取正在运行容器的 Shell。
{{% /capture %}}
{{% capture prerequisites %}}
{{< include "task-tutorial-prereqs.md" >}} {{< version-check >}}
{{% /capture %}}
{{% capture steps %}}
获取容器的 Shell
在本练习中,你将创建包含一个容器的 Pod。容器运行 nginx 镜像。下面是 Pod 的配置文件:
{{< codenew file="application/shell-demo.yaml" >}}
创建 Pod:
kubectl create -f https://k8s.io/examples/application/shell-demo.yaml
检查容器是否运行正常:
kubectl get pod shell-demo
获取正在运行容器的 Shell:
kubectl exec -it shell-demo -- /bin/bash
{{< note >}}
双破折号 "--" 用于将要传递给命令的参数与 kubectl 的参数分开。 note >}}
在 shell 中,打印根目录:
root@shell-demo:/# ls /
在 shell 中,实验其他命令。下面是一些示例:
root@shell-demo:/# ls /
root@shell-demo:/# cat /proc/mounts
root@shell-demo:/# cat /proc/1/maps
root@shell-demo:/# apt-get update
root@shell-demo:/# apt-get install -y tcpdump
root@shell-demo:/# tcpdump
root@shell-demo:/# apt-get install -y lsof
root@shell-demo:/# lsof
root@shell-demo:/# apt-get install -y procps
root@shell-demo:/# ps aux
root@shell-demo:/# ps aux | grep nginx
编写 nginx 的 根页面
在看一下 Pod 的配置文件。该 Pod 有个 emptyDir
卷,容器将该卷挂载到了 /usr/share/nginx/html
。
在 shell 中,在 /usr/share/nginx/html
目录创建一个 `index.html 文件:
root@shell-demo:/# echo Hello shell demo > /usr/share/nginx/html/index.html
在 shell 中,向 nginx 服务器发送 GET 请求:
root@shell-demo:/# apt-get update
root@shell-demo:/# apt-get install curl
root@shell-demo:/# curl localhost
输出结果显示了你在 index.html
中写入的文本。
Hello shell demo
当用完 shell 后,输入 exit
退出。
在容器中运行单个命令
在普通的命令窗口(而不是 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
{{% /capture %}}
{{% capture discussion %}}
当 Pod 包含多个容器时打开 shell
如果 Pod 有多个容器,--container
或者 -c
可以在 kubectl exec
命令中指定容器。
例如,您有个名为 my-pod 的容器,该 Pod 有两个容器分别为 main-app 和 healper-app。
下面的命令将会打开一个 shell 访问 main-app 容器。
kubectl exec -it my-pod --container main-app -- /bin/bash
{{% /capture %}}
{{% capture whatsnext %}}
{{% /capture %}}