This article explains the usage of the kubectl exec command for executing commands inside running containers.
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.
The basic syntax for the kubectl exec command is as follows:
Copy
Ask AI
kubectl exec
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.
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:
Copy
Ask AI
kubectl exec -n dev nginx -it -- /bin/bash
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:
Copy
Ask AI
kubectl exec -n dev nginx -- cat /usr/share/nginx/html/index.html
The resulting HTML output appears as follows:
Copy
Ask AI
<!DOCTYPE html><html><head><title>Welcome to nginx!</title><style>html { color-scheme: Light dark; }body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; }</style></head><body><h1>Welcome to nginx!</h1><p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p><p>For online documentation and support please refer to <a href="http://nginx.org/">nginx.org</a>.<br>Commercial support is available at <a href="http://nginx.com/">nginx.com</a>.</p><em>Thank you for using nginx.</em></body></html>
After reviewing a file, if you start an interactive shell by running:
Copy
Ask AI
kubectl exec -n dev nginx -it -- /bin/bash
You might see a prompt like this:
Copy
Ask AI
root@nginx:/# lsbin boot dev docker-entrypoint.sh etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var
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.
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: