kubectl-exec
Run commands inside a pod container
TLDR
Open Bash in a pod, using the first container by default
SYNOPSIS
kubectl exec [OPTIONS] POD [-c CONTAINER] [-- COMMAND [args...]]
PARAMETERS
-c, --container string
Select specific container; defaults to first in pod
-i, --stdin
Pass stdin to container for input
-t, --tty
Allocate pseudo-TTY for interactive shells
--attach
Attach to running process output
-n, --namespace string
Target namespace (default current)
-e, --env=[]
Set environment variables in container
--as string
Impersonate user in namespace
--context string
Kubeconfig context to use
--dry-run=client|server|none
Dry run without execution
--quiet
Suppress pod/container info output
--pod-running-timeout duration
Wait for pod to run (default 1m)
DESCRIPTION
kubectl exec executes a command inside a running container in a Kubernetes pod, enabling debugging and inspection without restarting pods.
Key features include stdin/stdout forwarding for interactive sessions (using -it), container selection via -c, and namespace scoping with -n. It supports one-off commands like ls or full shells like /bin/bash.
Use cases: troubleshoot crashes by checking processes (ps aux), verify configs (cat /etc/app.conf), test connectivity (curl localhost), or debug env vars (env). Output mirrors local execution, with TTY support for vim/nano.
Streams I/O bidirectionally but requires the container to have the command/binary. RBAC must allow create podexec on the pod. Ideal for dev/test; avoid in prod for security.
CAVEATS
Security risk: grants shell access; use RBAC to restrict. Fails if no running containers. Interactive TTY may drop on network issues. Not for persistent changes (pod restarts lose them).
EXAMPLES
kubectl exec mypod -- ls -la /app
kubectl exec -it -n default mypod -- /bin/sh
kubectl exec mypod -c sidecar -- cat /var/log/app.log
PERMISSIONS
Needs pods/exec RBAC role. Check with kubectl auth can-i exec pod --namespace=foo.
HISTORY
Part of kubectl CLI since Kubernetes v1.0 (2014), developed by Google/CNCF. Evolved for better container orchestration; added TTY/stdin in early 1.x releases.


