kubectl exec: Run Commands in Pods in CI
Run a command inside a container of a running pod.
kubectl exec executes a process in an existing pod container. In CI it runs database migrations, one-off scripts, or health checks against a live workload. The pod must be Running and the command must exist inside the container image.
Common flags
POD -- CMD ARGS- command after -- runs in the pod-c CONTAINER- pick a container in a multi-container pod-it- interactive TTY (rarely used in CI; prefer non-interactive)-n NAMESPACE- target namespace
Example in CI
Run database migrations inside the api pod.
shell
POD=$(kubectl get pod -l app=api -n prod -o jsonpath='{.items[0].metadata.name}')
kubectl exec "${POD}" -n prod -- npm run migrateCommon errors in CI
- exec: "X": executable file not found in $PATH - the command is not in the image
- unable to upgrade connection: container not found - pod not Running yet
- error: unable to upgrade connection: Forbidden - RBAC denies pods/exec
Key takeaways
- Runs a process inside a running pod container.
- Common for migrations and one-off scripts in CI; skip -it in pipelines.
- The command must exist in the image and the pod must be Running.
Related guides
kubectl logs: Capture Container Logs in CIFetch container logs in CI: selector, previous, and tail flags, a debug example, and the errors you hit when…
kubectl get pods: Inspect Pods in CIList and inspect pods in CI: output and selector flags, a scripting example, and the errors that point to acc…
kubectl describe: Debug Resources in CIShow detailed resource state and events in CI: usage, a debugging example, and the errors that indicate the w…