Skip to content
Latchkey

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 migrate

Common 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

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →