Sign In

Curriculum 12: Pod Management

kubectl exec

15 min · 25 XP

Executing Commands Inside Pods with kubectl exec

The kubectl exec command lets you run commands directly inside a running container. This is essential for debugging, inspecting state, and performing one-off tasks without rebuilding images.

Basic Command Execution

Run a single command inside a pod:

kubectl exec my-pod -- ls /app
kubectl exec my-pod -- cat /etc/resolv.conf
kubectl exec my-pod -- env

The -- separator prevents kubectl from interpreting pod arguments as its own flags.

Interactive Shell Sessions

Use -it flags to open an interactive terminal session. The -i flag passes stdin, and -t allocates a TTY:

kubectl exec -it my-pod -- /bin/bash
kubectl exec -it my-pod -- /bin/sh

Once inside, you can explore the filesystem, check processes, test network connectivity, or inspect application state in real time.

Multi-Container Pods

When a pod has multiple containers, you must specify which container to exec into using --container (or -c):

kubectl exec -it my-pod --container nginx -- /bin/sh
kubectl exec my-pod -c sidecar -- cat /var/log/proxy.log

Without this flag, kubectl defaults to the first container defined in the pod spec.

Practical Debugging Examples

# Check network connectivity from inside a pod
kubectl exec my-pod -- curl -s http://my-service:8080/health

# Inspect mounted secrets
kubectl exec my-pod -- ls /var/run/secrets/kubernetes.io/serviceaccount

# Run a database query
kubectl exec -it postgres-pod -- psql -U admin -d mydb

Always prefer exec for temporary inspection. For persistent debugging needs, consider ephemeral containers instead.