Skip to main content
In this lesson, we will explore the purpose and usage of the kubectl exec command, which functions very similarly to docker exec. This powerful command enables you to execute commands inside a running container, making it an invaluable tool for container management and troubleshooting.

Basic Syntax

The basic syntax for the kubectl exec command is as follows:
When using this command, you need to specify the namespace and the pod name. If the pod contains multiple containers, include the container name by using the -c flag. For a pod with a single container, you only need to append -- followed by the command you wish to execute.

Listing Container Filesystem Contents

For instance, if you want to view the contents of a container’s filesystem, you can run:
The output will display a directory listing similar to the following:

Getting an Interactive Shell

Sometimes it is more convenient to enter into an interactive shell session within the container. For this purpose, add the -i (interactive) and -t (tty) flags. For example:
Once you have an interactive shell, you can execute various commands to inspect file permissions, navigate directories, or install debugging tools. For example, to display the content of the default nginx index page, you would run:
The resulting HTML output appears as follows:
After reviewing a file, if you start an interactive shell by running:
You might see a prompt like this:

Use Cases and Best Practices

This approach is especially useful when you need to inspect file permissions, install debugging utilities, or run diagnostic tools such as tcpdump to gain insights into the container’s behavior. However, it is important to note that:
Avoid using kubectl exec in production environments as it may interfere with the running workload. Instead, limit its use to development or staging environments and consider using more robust troubleshooting methods for production setups.

Next Steps

In subsequent lessons, we will explore advanced techniques and diagnostic methods that are more suitable for addressing issues in production workloads. For further information, check out these resources:

Watch Video