# 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:**

- `-i`: Keep STDIN open
- `-t`: Allocate a TTY (for interactive commands like bash or sh)
- `--container`: Specify a container if the pod has multiple containers

### **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**

- `kubectl exec` gives cluster users _shell-level access_ to containers.
- Avoid granting this permission widely; tie it to specific roles via RBAC.
- Limit `exec` rights for untrusted users to reduce risk of privilege escalation.

#### **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**

- **`kubectl debug`**: Introduced in newer versions of Kubernetes, allows temporary debug containers to be attached for deeper analysis.
- **`kubectl logs`**: For passive log inspection, without executing anything inside.
- **`stern` / `kail`**: Third-party tools to tail logs across pods, often used before resorting to `exec`.

* * *

### **Best Practices**

- Always check if a pod has more than one container and specify the correct one with `-c`.
- Use `kubectl exec` for short-lived troubleshooting—not as a substitute for proper logging or observability.
- Audit the use of `kubectl exec` in production clusters for security compliance.

* * *

### **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**

- [Official Kubernetes documentation](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#exec)
- [Kubernetes security best practices (RBAC & audit logging):](https://kubernetes.io/docs/reference/access-authn-authz/rbac/)
- [`kubectl debug` command](https://kubernetes.io/docs/tasks/debug/debug-application/debug-running-pod/)
