kubectl exec

在运行中的容器内执行命令

语法

kubectl exec <pod-name> [-c container] -- <command> [args]

参数

参数说明示例级别
-it 交互式终端(分配 TTY) kubectl exec -it web-pod -- /bin/bash 常用
-c --container 指定容器(多容器 Pod) kubectl exec -it web-pod -c sidecar -- sh 常用
-n --namespace 指定命名空间 kubectl exec -it web-pod -n production -- sh 常用

示例

进入容器 Shell

kubectl exec -it web-app-6f7b8c9d-k2m4n -- /bin/bash
如果没有 bash 可以用 /bin/sh

执行单条命令

kubectl exec web-pod -- cat /etc/config/app.conf
不需要交互时不用 -it

查看容器环境变量

kubectl exec web-pod -- env
排查配置注入问题

测试网络连通性

kubectl exec web-pod -- curl -s http://backend-svc:8080/health
从 Pod 内部测试服务发现

常见错误

OCI runtime exec failed: exec failed: unable to start container process 容器中没有指定的命令,尝试 /bin/sh 代替 /bin/bash
container not running 容器未处于 Running 状态,检查 Pod 状态

技巧

相关命令