Sub topic 17
Debugging with kubectl debug
This chapter assumes you can read kubectl logs output and the terminated state of a container, as covered in the earlier chapters on previous logs and exit codes. Logs and events explain most failures. Sometimes they do not. The image may have no shell, or the container may exit before you can look around. kubectl debug handles both cases.
When logs are not enough
Reach for kubectl debug when:
- The app logs nothing useful, and you need to check DNS, network reachability, or files from inside the pod.
- The image is minimal (distroless or
scratch), sokubectl exechas no shell to run. - The container exits immediately, so there is nothing running to
execinto.
These two situations call for different forms of the command.
Attach an ephemeral container
An ephemeral container is a temporary container added to a pod that is already running. It shares the pod's network namespace. With --target, it also shares the process namespace of the named container, so you can see that container's processes.
kubectl debug -it web --image=busybox:1.36 --target=appInside the shell you can run nslookup, wget, or ps to test what the app sees. Ephemeral containers cannot be removed from a pod once added. They also cannot be restarted and do not support probes or resource settings. They disappear when the pod is replaced.
Debug a copy of the pod
If the container keeps crashing, attaching to it will not help. Create a copy of the pod and replace the app container's command with a shell:
kubectl debug web -it --copy-to=web-debug --container=app -- shThe copy is a new pod named web-debug. The original pod stays untouched, so you can inspect it as before. In the copy, the app does not start. You land in a shell inside the same image, with the same environment variables, mounts, and Secrets. From there you can run the original start command by hand and watch it fail.
Use the table to choose between the two forms.
| Situation | Form | Original pod affected? |
|---|---|---|
| Container is running, no shell in image | Ephemeral container with `--image` and `--target` | Yes, the pod gains a container |
| Container crashes on start | Copy with `--copy-to` and a replaced command | No |
Clean up
The copy keeps running after you leave the shell, and it uses node resources. Delete it when you finish:
kubectl delete pod web-debugExercise
A pod runs a distroless image and kubectl exec -it web -- sh fails because there is no shell. The container is running normally. Which kubectl debug form do you use, and why not --copy-to?
Show answer
Use an ephemeral container: kubectl debug -it web --image=busybox:1.36 --target=app. It adds a shell-capable container to the running pod and shares its network and, with --target, its processes. --copy-to is for a container that crashes on start, and it would replace the command in a copy instead of inspecting the live pod.