kubectl exec: Executing Commands in Containers
What You'll Learn
You'll learn how to run commands directly inside running containers using kubectl exec for debugging and troubleshooting your Kubernetes workloads.
Why kubectl exec Matters
Imagine you're a ship captain who needs to inspect the engine room while the ship is sailing. You don't want to stop the vessel—you just need to peek inside and check what's happening. That's exactly what kubectl exec does: it lets you "enter" a running container and execute commands without restarting it.
When your application misbehaves in production, you need to investigate logs, check file systems, test network connectivity, or verify configurations—all while the container keeps running.
How kubectl exec Works
The basic syntax is straightforward:
kubectl exec <pod-name> -- <command>
For interactive sessions (like getting a shell):
kubectl exec -it <pod-name> -- /bin/bash
The -i flag keeps stdin open (interactive), and -t allocates a pseudo-terminal (TTY), giving you a proper shell experience.
If your pod has multiple containers, specify which one:
kubectl exec -it <pod-name> -c <container-name> -- /bin/sh
Common Troubleshooting Scenarios
- Check application logs:
kubectl exec my-pod -- cat /var/log/app.log - Test network connectivity:
kubectl exec my-pod -- ping google.com - Inspect environment variables:
kubectl exec my-pod -- env - Debug file permissions:
kubectl exec my-pod -- ls -la /app
Security Note
kubectl exec grants direct access to container internals, so proper RBAC policies should restrict who can execute commands in production environments.
Key Takeaway: kubectl exec is your debugging Swiss Army knife—use it to run commands inside live containers for real-time troubleshooting without disrupting your running workloads.