What Is kubectl exec? Run Commands in Kubernetes Pods

kubectl exec

Definition

kubectl exec is a command-line utility that lets you run a command inside a running container in a Kubernetes pod, giving you direct, real-time access to the container’s shell or environment.

What Does kubectl exec Do?

When you need to interact with a container running in your cluster—whether to troubleshoot, check logs, test commands, or manually fix a process—kubectl exec gives you a way to do it interactively. It’s similar to using ssh on a VM, but for containers in Kubernetes.

This command executes a user-defined command directly inside the container’s runtime environment, optionally giving you a full shell session.

Basic Syntax

kubectl exec [POD_NAME] -- [COMMAND]

Or to enter an interactive shell:

kubectl exec -it [POD_NAME] -- /bin/sh

Flags:

Common Use Cases

🔍 1. Debugging Pods

You can open a shell session in a pod to manually inspect logs, config files, or runtime behavior:

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

🛠 2. Running One-off Commands

Need to test if an env var is set or check filesystem content?

kubectl exec my-app-pod -- printenv
kubectl exec my-app-pod -- ls /app

⚙️ 3. Inspecting Environment Variables

kubectl exec my-app-pod -- env

🔁 4. Restarting Services (not containers)

If your app supports it:

kubectl exec my-app-pod -- pkill -HUP myapp

🧪 5. Troubleshooting with Network Tools

If tools like curl, nslookup, or ping are installed:

kubectl exec -it my-app-pod -- curl http://example.com

Example: Exec into a Pod with Multiple Containers

If your pod contains multiple containers (e.g., a sidecar pattern), you must specify which one to target:

kubectl exec -it my-pod -c main-app-container -- /bin/bash

Things to Watch Out For

Security Implications

Not All Images Have a Shell

Some images like nginx:alpine might not include /bin/bash or even /bin/sh. In such cases:

kubectl exec my-pod -- ls /

…may work, but a shell might not be available.

Requires a Running Pod

You cannot exec into a pod that’s in CrashLoopBackOff, Pending, or Terminated state.


Alternatives & Related Tools


Best Practices


Real-World Example: Debugging a 502 Error

You’re seeing a 502 Bad Gateway error on your frontend. You suspect your API backend is the issue.

kubectl exec -it backend-pod-xyz -- curl localhost:3000/health

The command times out, suggesting the backend process isn’t running. You run:

kubectl exec backend-pod-xyz -- ps aux

You find the process didn’t start. Then:

kubectl exec backend-pod-xyz -- cat /var/log/app.log

You discover a missing env var. Problem solved—without rebuilding the image.

Resources