0
0
Kubernetesdevops~5 mins

kubectl exec for container access in Kubernetes - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you need to look inside a running container to check logs, files, or run commands. kubectl exec lets you open a terminal inside a container to do this directly.
When you want to debug a running application by checking its files or logs inside the container.
When you need to run a quick command inside a container without changing its image or restarting it.
When you want to inspect the environment variables or configuration inside a container.
When you want to test connectivity or run network commands inside a container.
When you want to manually fix a problem inside a container before automating a solution.
Commands
This command lists all running pods in the current namespace so you can find the pod name to access.
Terminal
kubectl get pods
Expected OutputExpected
NAME READY STATUS RESTARTS AGE example-pod 1/1 Running 0 10m
This command opens an interactive shell inside the container of the pod named example-pod. The -it flags allow you to interact with the shell.
Terminal
kubectl exec -it example-pod -- /bin/sh
Expected OutputExpected
#
-i - Keep stdin open so you can type commands
-t - Allocate a terminal so the shell works interactively
This command exits the shell inside the container and returns you to your local terminal.
Terminal
exit
Expected OutputExpected
No output (command runs silently)
Key Concept

If you remember nothing else from this pattern, remember: kubectl exec -it pod-name -- /bin/sh lets you open a live terminal inside a container to inspect or fix it.

Common Mistakes
Running kubectl exec without -it flags
Without -it, you cannot interact with the shell, so commands that need input or a terminal will fail or hang.
Always use both -i and -t flags together when opening a shell inside a container.
Using the wrong shell path like /bin/bash when the container only has /bin/sh
If the shell does not exist in the container, the command will fail with an error.
Check the container image documentation or try /bin/sh which is more common and lightweight.
Not specifying the command after --
kubectl exec needs a command to run inside the container; without it, the command will fail.
Always specify the command to run after --, for example /bin/sh or /bin/bash.
Summary
Use kubectl get pods to find the pod name you want to access.
Use kubectl exec -it pod-name -- /bin/sh to open an interactive shell inside the container.
Use exit to leave the container shell and return to your local terminal.