kubectl exec: Executing Commands in Kubernetes Containers

The kubectl exec command allows you to run commands directly inside a container within a Kubernetes pod. This is an invaluable tool for debugging, inspecting running processes, or performing quick administrative tasks without exposing ports or restarting containers. It’s the Kubernetes equivalent of docker exec.

Finding Your Target Pod or Deployment

Before you can execute a command inside a container, you need to identify the target pod or deployment.

List Deployments (to find associated pods)

kubectl get deployments --all-namespaces

Once you find the deployment, you can use its name to target the pod, or get the specific pod name.

List Pods

It’s often more direct to list pods if you know the namespace.

kubectl get pods -n <namespace>
# Example:
kubectl get pods -n uat

Executing Commands

The kubectl exec command requires the pod name (or a resource that resolves to a pod, like deploy/<deployment-name>), the namespace, and the command you wish to execute.

Getting an Interactive Shell

This is a common use case for interactive debugging, letting you navigate the container’s file system and run commands.

# Execute a bash shell in a container within a deployment's pod
kubectl exec -n <namespace> -it deploy/<deployment-name> -- /bin/bash
# Example:
kubectl exec -n uat -it deploy/unify-controller -- /bin/bash
 
# Execute a bash shell in a specific pod
kubectl exec -n <namespace> -it <pod-name> -- /bin/bash
 
# Often, /bin/sh is more commonly available in minimal container images
kubectl exec -n <namespace> -it <pod-name> -- /bin/sh
  • -n <namespace>: Specifies the namespace where the pod is running.
  • -it: Combines -i (interactive) and -t (pseudo-TTY), which is necessary for a full interactive shell experience.
  • deploy/<deployment-name>: A convenient way to target a pod managed by a deployment. You can also use pod/<pod-name>.
  • --: Separates kubectl arguments from the command to be executed inside the container.

Running a Single Command

You can also run non-interactive commands to get output or perform a specific action.

# List files in the root directory of a container
kubectl exec -n <namespace> <pod-name> -- ls -la /
 
# Check the version of an installed package
kubectl exec -n <namespace> <pod-name> -- cat /etc/os-release

Specifying a Container (for multi-container pods)

If your pod has multiple containers, you must specify which container to execute the command in using the -c flag.

kubectl exec -n <namespace> -it <pod-name> -c <container-name> -- /bin/bash