0
0
Kubernetesdevops~5 mins

Executing commands in Pods in Kubernetes - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you need to look inside a running container to check logs, fix issues, or run quick commands. Kubernetes lets you run commands directly inside your Pods without stopping them.
When you want to check the contents of a file inside a running container.
When you need to debug an application by running shell commands inside the Pod.
When you want to check environment variables or configuration inside the container.
When you want to run a quick database query inside a Pod running a database.
When you want to test connectivity or network tools inside the Pod.
Commands
This command lists all running Pods in the current namespace so you can find the Pod name to run commands inside.
Terminal
kubectl get pods
Expected OutputExpected
NAME READY STATUS RESTARTS AGE example-pod 1/1 Running 0 10m
This runs the 'ls /app' command inside the 'example-pod' container to list files in the /app directory.
Terminal
kubectl exec example-pod -- ls /app
Expected OutputExpected
main.py config.yaml README.md
-- - Separates kubectl command options from the command to run inside the Pod
This opens an interactive shell inside the 'example-pod' container so you can run multiple commands manually.
Terminal
kubectl exec -it example-pod -- /bin/sh
Expected OutputExpected
/ #
-i - Keep stdin open for interactive commands
-t - Allocate a terminal for the interactive session
This exits the interactive shell inside the Pod 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: use 'kubectl exec' with '--' to run commands inside a Pod safely.

Common Mistakes
Running 'kubectl exec example-pod ls /app' without '--' before the command
kubectl treats 'ls /app' as its own arguments, causing errors or unexpected behavior.
Always include '--' before the command to run inside the Pod, like 'kubectl exec example-pod -- ls /app'.
Trying to run interactive shell without '-it' flags
Without '-it', you cannot interact with the shell, so commands may hang or fail.
Use 'kubectl exec -it example-pod -- /bin/sh' to open an interactive shell.
Summary
Use 'kubectl get pods' to find the Pod name you want to access.
Run 'kubectl exec POD_NAME -- COMMAND' to execute a command inside the Pod.
Add '-it' flags to run an interactive shell inside the Pod.
Use '--' to separate kubectl options from the command inside the Pod.