The command docker exec is a tool that allows us to run a new process inside a container that is already in a running state.
Imagine this situation: You have your Nginx server running perfectly in the background (-d). Everything seems fine, but suddenly, the website gives an Error 500.
You need to check the configuration file, verify if the disk is full, or ping the database from inside.
In the world of Virtual Machines, you would connect via SSH. But in Docker, SSH is not used. Instead, we have a much more powerful and direct command: docker exec.
Why not use SSH?
It’s a classic question. Why not install openssh-server on my Docker image to connect with PuTTY? Because it’s an anti-pattern.
- ❌ Unnecessary weight: You are adding a heavy service to a container that should be lightweight.
- ❌ Security: You have to manage keys, users, and open port 22. More attack vectors.
- ❌ Complexity: You have to configure systemd or supervisord to run two processes at the same time (your app + ssh), which goes against the “one container, one process” philosophy.
Docker already has its own secure backdoor: it’s the Docker Socket via docker exec. Use it.
What is docker exec?
This command allows us to run a new process inside a container that is already running.
docker exec [OPTIONS] <CONTAINER_NAME> <COMMAND>
- <CONTAINER_NAME>: The name or ID of the container in which we want to execute the command.
- <COMMAND>: The command we wish to run inside the container.
- [OPTIONS]: Additional options to customize the command execution.
Basic example Suppose we have a running container named my_container that is running a web server. If we want to see the files inside the container, we can use docker exec to list the contents of the current directory:
docker exec my_container ls -l
This command will run ls -l inside the my_container container and display the file listing in the terminal.
