DEV Community

Cover image for Kubectl Demystified: Mastering the `kubectl exec` Command
Naveen.S
Naveen.S

Posted on • Edited on

Kubectl Demystified: Mastering the `kubectl exec` Command

Kubernetes has become the cornerstone of container orchestration, and kubectl is the primary command-line tool for interacting with Kubernetes clusters. Among its many commands, kubectl exec is a powerful utility for debugging and troubleshooting. This guide will explain what kubectl exec is, when to use it, and provide practical examples to prepare you for real-world scenarios and the Certified Kubernetes Administrator (CKA) exam.

What is kubectl exec?

kubectl exec allows you to execute commands directly inside a running container within a Kubernetes pod. It’s akin to using docker exec for containers but tailored for Kubernetes pods. This command is invaluable for debugging, inspecting logs, or performing ad-hoc tasks in your containerized environment.

How It Works

When you run kubectl exec, the Kubernetes API connects to the specified pod and container, then executes the command you provide. If you request an interactive shell (e.g., /bin/bash), kubectl establishes a terminal session with the container.

Basic Syntax

kubectl exec [POD_NAME] -- [COMMAND]
Enter fullscreen mode Exit fullscreen mode
  • [POD_NAME]: The name of the target pod.
  • --: Separates kubectl options from the command to run inside the container.
  • [COMMAND]: The command to execute (e.g., ls, cat, /bin/bash).

When to Use kubectl exec?

Common use cases include:

  1. Debugging: Inspect logs, environment variables, or running processes.
  2. Testing Connectivity: Verify network access from the container (e.g., using curl or ping).
  3. Modifying Configurations: Temporarily edit files (e.g., configuration files).
  4. Diagnosing Performance: Check resource usage with tools like top or free.
  5. Multi-Container Pods: Access a specific container in pods with multiple sidecars.

Syntax and Common Options

Key Flags

  • -i or --stdin: Keep stdin open for interactive commands.
  • -t or --tty: Allocate a pseudo-terminal for a shell session.
  • -c or --container: Specify a container in a multi-container pod.
  • -n or --namespace: Target a pod in a specific namespace.

Combine -i -t (or -it) for interactive shell access:

kubectl exec -it [POD_NAME] -- /bin/bash
Enter fullscreen mode Exit fullscreen mode

Practical Examples with Explanations

Example 1: Run a Simple Command

Check the contents of the /app directory in a pod named web-server:

kubectl exec web-server -- ls /app
Enter fullscreen mode Exit fullscreen mode

Explanation: Lists files in the /app directory without entering an interactive shell.

Example 2: Start an Interactive Shell

Access a Bash shell in the web-server pod:

kubectl exec -it web-server -- /bin/bash
Enter fullscreen mode Exit fullscreen mode

Note: If Bash isn’t available (common in minimal images like Alpine Linux), use /bin/sh.

Example 3: Target a Specific Container

In a pod named api-gateway with containers app and logger, access the logger container:

kubectl exec -it api-gateway -c logger -- /bin/sh
Enter fullscreen mode Exit fullscreen mode

Explanation: The -c logger flag specifies the container name.

Example 4: Check Environment Variables

List all environment variables in the web-server pod:

kubectl exec web-server -- env
Enter fullscreen mode Exit fullscreen mode

Example 5: Test Network Connectivity

Verify if the pod can reach google.com:

kubectl exec web-server -- curl -I https://google.com
Enter fullscreen mode Exit fullscreen mode

Example 6: View Running Processes

Inspect processes in the web-server pod:

kubectl exec web-server -- ps aux
Enter fullscreen mode Exit fullscreen mode

Example 7: Edit a File (If Editor is Installed)

Modify config.yaml in the web-server pod using vi:

kubectl exec -it web-server -- vi /etc/config/config.yaml
Enter fullscreen mode Exit fullscreen mode

Note: Most minimal containers lack text editors. Use kubectl cp to copy files instead.

Example 8: Execute Commands in a Namespace

Run date in a pod located in the staging namespace:

kubectl exec -n staging web-server -- date
Enter fullscreen mode Exit fullscreen mode

Best Practices and Warnings

  1. Debugging Only: Avoid using kubectl exec for routine operations. Configuration changes made this way are ephemeral.
  2. Security: Limit access to exec via Role-Based Access Control (RBAC).
  3. Minimal Images: Many containers lack tools like curl or vi. Use kubectl logs or kubectl cp as alternatives.

CKA Exam Tips

  1. Speed Matters: Memorize the syntax to save time:
   kubectl exec -it [POD] -c [CONTAINER] -- sh
Enter fullscreen mode Exit fullscreen mode
  1. Multi-Container Pods: Always specify -c [CONTAINER] if the pod has multiple containers.
  2. Troubleshooting Tasks: Expect scenarios where you’ll need to:
    • Check if a file exists in a container.
    • Verify environment variables.
    • Test internal service connectivity (e.g., curl http://service-name).

Image description

Conclusion

kubectl exec is a vital tool for debugging Kubernetes workloads. Whether you’re inspecting logs, testing network policies, or preparing for the CKA exam, mastering this command will enhance your Kubernetes troubleshooting skills. Remember to use it judiciously and prioritize declarative configurations for long-term changes.

Final Checklist for the CKA Exam:

  • Practice executing commands in multi-container pods.
  • Familiarize yourself with minimal shells like /bin/sh.
  • Use kubectl exec --help to review flags quickly during the exam.

With these skills, you’ll be well-equipped to tackle real-world Kubernetes challenges and ace the CKA exam! 🚀

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay