This tutorial aims to show you how to work with the Docker exec command to execute commands in running containers.
Basic Usage
Working with Docker exec is very simple. We start by calling the docker exec command followed by the container name or id and the command to execute.
For example, to run the echo command in container Debian, we use the command as:
The command spawns a shell of the Debian container and executes the echo command. An example output appears below:
To get the name or an ID of the running containers, use the command:
Docker Exec Options
Docker exec command supports various options to modify the functionality of the commands. It supports the following functions.
- -i – This option keeps the STDIN.
- -t – Spawns a pseudo TTY
- -u – Specifies the username or UID.
- -w – Working directory
- -p – allocates extended privileges to the command.
- -d – runs in detached mode.
- -e – sets environment variables.
Docker Exec Sh
In most cases, we need a shell instance into the container to execute raw commands. To do this, we use the docker exec command.
The command above launches an interactive shell. It is good to ensure bash executable exists before the running command.
If bash or any shell you wish to use is unavailable, use sh in the command below:
As you can see, you have an interactive shell session where you can execute commands.
Exec as Root
To exec command as root, use the -u option. The option requires a username or UID of the user. For example:
$ root
In the above command, we use the UID of the root user to execute the whoami command as root.
To use the username instead of the user UID, use the command:
$ root
The command above can help when you want to troubleshoot or perform tasks that require elevated privileges.
Conclusion
That is all for the docker exec command.
We have discussed using docker exec to run commands in your running containers and spawn a shell session. Finally, we covered how to run commands as root using username and UID.