Run commands or get a shell in the container with `docker exec`
"Servers," whether they're bare metal, or a VM, or even an infrastructure container typically have a number of different daemons running, including SSH. Even in the most automated of environments, most of us depend on being able to "get in" to the server via SSH to take a look at problems, trigger a database dump, or any number of other tasks that need doing.
But, typical Docker containers don't have SSH running, meaning we can't get in that way. That focus on running just one service per container is a good thing, but it means we've got to use a different method to do the ad-hoc maintenance and investigations that are inevitable in the operation of any application.
The solution is docker exec ...
.
The nearest equivalent of SSHing into a Docker container is to docker exec -it <container name or UUID> bash
(you may have to specify a different shell or a complete path if bash
is not in your path). However, you can run any executable in the container.
Consider the following examples:
# get an interactive shell in the container
docker exec -it <container name> bash
# do a database dump from a MySQL container to your local computer
docker exec <container name> sh -c 'exec mysqldump --all-databases -uroot -p"$MYSQL_ROOT_PASSWORD"' > all-databases.sql
There are some things to be aware of:
- If the container is stopped, docker exec will fail with an error.
- Take careful note of shell parsing, both your local and remote shells. The MySQL example is worthy of special attention in that respect.