Sometimes, we want to run another process inside an already-running container. A typical reason could be to try to debug a misbehaving container. How can we do this? First, we need to know either the ID or the name of the container, and then we can define which process we want to run and how we want it to run. Once again, we use our currently-running quotes container and we run a shell interactively inside it with the following command:
$ docker container exec -i -t quotes /bin/sh
The flag -i signifies that we want to run the additional process interactively, and -t tells Docker that we want it to provide us with a TTY (a terminal emulator) for the command. Finally, the process we run is /bin/sh.
If we execute the preceding command in our Terminal, then we will be presented with a new prompt. We're now in a shell inside the quotes container. We can easily prove that by, for example, executing the ps command, which will list all running processes in the context:
# / ps
The result should look somewhat similar to this:
We can clearly see that the process with PID 1 is the command that we have defined to run inside the quotes container. The process with PID 1 is also named the main process.
Leave the container by entering exit at the prompt. We cannot only execute additional processes interactive in a container. Please consider the following command:
$ docker container exec quotes ps
The output evidently looks very similar to the preceding output:
We can even run processes as daemon using the flag -d and define environment variables using the -e flag variables as follows:
$ docker container exec -it \
-e MY_VAR="Hello World" \
quotes /bin/sh
# / echo $MY_VAR
Hello World
# / exit