0
0
KubernetesHow-ToBeginner · 3 min read

How to Use kubectl exec to Run Commands in Kubernetes Pods

Use kubectl exec to run commands inside a Kubernetes pod. The basic syntax is kubectl exec [pod-name] -- [command], which lets you execute commands directly in the pod's container.
📐

Syntax

The basic syntax of kubectl exec is:

  • kubectl exec [pod-name]: Specifies the pod where the command will run.
  • --: Separates kubectl options from the command to run inside the pod.
  • [command]: The command you want to execute inside the pod.
  • Optional flags like -it enable interactive terminal mode.
bash
kubectl exec [pod-name] -- [command]

kubectl exec -it [pod-name] -- [command]
💻

Example

This example shows how to open an interactive shell inside a pod named my-pod. It demonstrates running a bash shell interactively.

bash
kubectl exec -it my-pod -- /bin/bash
Output
root@my-pod:/#
⚠️

Common Pitfalls

  • Forgetting the -- separator causes kubectl to misinterpret the command.
  • Not using -it when running interactive commands like shells will cause no terminal input.
  • Trying to exec into a pod that is not running will fail.
  • Specifying the wrong container in multi-container pods requires the -c [container-name] flag.
bash
Wrong (missing --):
kubectl exec my-pod /bin/bash

Right:
kubectl exec -it my-pod -- /bin/bash
📊

Quick Reference

CommandDescription
kubectl exec my-pod -- ls /Run 'ls /' inside 'my-pod' non-interactively
kubectl exec -it my-pod -- /bin/bashOpen interactive bash shell inside 'my-pod'
kubectl exec -it my-pod -c my-container -- /bin/shExec into specific container in multi-container pod
kubectl exec my-pod -- cat /etc/hostsDisplay contents of /etc/hosts file inside pod

Key Takeaways

Always use -- to separate kubectl options from the command inside the pod.
Use -it flags for interactive commands like shells.
Specify the container with -c if the pod has multiple containers.
Ensure the pod is running before using kubectl exec.
kubectl exec lets you run commands directly inside a pod's container.