Executing Commands
When deploying applications with Docker, you typically just let the container do its thing. For example, a container might start its own web server based on the image configuration, and you don’t need to run any manual commands.
However, it is possible to run commands inside a running container! This is similar to the container version of SSH-ing into a remote server to run a command.
The docker exec Command
You can use the docker exec command to run a one-off command inside a running container.
-
First, list your running containers to get the container ID:
docker ps -
Run a command (like
ls) from inside the container:docker exec CONTAINER_ID ls -
You can also run commands that modify the container’s state, such as creating a file:
docker exec CONTAINER_ID touch hacker.log
Example: Checking Running Processes
You can use exec to investigate the container’s environment. For instance, if you want to know what software is serving a webpage on port 80 inside the container, you could use netstat to see which programs are bound to which ports:
docker exec CONTAINER_ID netstat -ltnp