kubectl exec
- Docker & Kubernetes course
- Intermediate
- Lesson 73/82
- 4 min
Learn to run commands inside a Pod with kubectl exec.
kubectl exec
If logs aren't enough, you look inside the container: is the config file right, did the environment variables arrive, does the service name resolve?
kubectl exec -it deploy/api -- sh
$ printenv | grep DB_
$ cat /etc/resolv.conf
$ wget -qO- http://db:5432 || echo "bağlantı yok"
kubectl exec deploy/api -- ls -l /etc/ayarSmall (distroless, scratch) images may have no shell; in that case exec doesn't work.
kubectl debug
kubectl debug adds a temporary (ephemeral) container full of tools to a running pod; with --target it sees the target container's processes. It's also used to inspect a copy of the pod or the node itself:
kubectl debug -it api-xyz --image=busybox:1.36 --target=api
kubectl debug api-xyz -it --copy-to=api-kopya --container=api -- sh
kubectl debug node/worker-1 -it --image=ubuntu:24.04Practice Look inside
Write three commands: run printenv DB_HOST in deploy/api; run cat /etc/resolv.conf in deploy/api; add an interactive debug container with the busybox:1.36 image targeting the api container to the api-xyz pod.
Starter code
# buraya yazSample solution
kubectl exec deploy/api -- printenv DB_HOST
kubectl exec deploy/api -- cat /etc/resolv.conf
kubectl debug -it api-xyz --image=busybox:1.36 --target=apiExpected output
db search magaza.svc.cluster.local svc.cluster.local cluster.local nameserver 10.96.0.10 Targeting container "api". If you don't see processes from this container it may be because the container runtime doesn't support this feature. / #
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is used to debug an image that has no shell?
- Adding a temporary debug container with kubectl debug Correct answer
- kubectl exec -it -- sh
- Deleting the image
- kubectl logs
Explanation: kubectl debug adds an ephemeral container with tools to the pod.
2 Add a debug container to the pod.
kubectl ____ -it api-xyz --image=busybox:1.36 --target=api
kubectl debug -it api-xyz --image=busybox:1.36 --target=api
Explanation: debug adds an ephemeral container.
3 Match.
| Term | Meaning |
|---|---|
exec -it ... -- sh |
Shell in the container |
debug --target |
Temporary container with tools |
--copy-to |
Inspect in a pod copy |
debug node/ |
Inspect the node |