Card 05/ 06

WalkthroughDifficulty: Intermediate2 min

Opening a Shell Inside a Running Container With docker exec

The right place to look around, and the wrong place to fix anything.

docker exec runs an extra command inside a container that is already running, and with -it that command can be a shell: a command-line prompt you type into. It is how you check, from the inside, whether a file is where you expect or a directory holds what you thought.

Sooner or later you need to stand inside a running container and look around: is the config file where you think, is the port really open, does the directory you mounted contain what you expected. The steps below use a running nginx web server container called web, started with docker run -d --name web nginx, or any running container you have.

Getting a prompt inside a container that is already running

Run a single command in it

bash
docker exec web ls /usr/share/nginx/html
50x.html
index.html

exec starts a second process inside the running container, here ls, which lists the files nginx serves. The first process, nginx itself, carries on untouched.

Ask for a shell instead

bash
docker exec -it web sh
# whoami
root
# exit

-i keeps the input open so what you type reaches the shell, and -t gives it a terminal to draw a prompt on. Without both, the shell starts and has nothing to talk to. sh is the basic shell most images include; exit leaves it and the container keeps running. You know you are inside when the prompt changes to # and whoami answers root, the user the container's program runs as.

Remember what you changed

Anything you edit in there lives in the container's writable layer, its private area for changed files, and disappears with the container. It is the right place to look and the wrong place to fix.

The command people reach for by mistake is docker run, which starts a new container from the image: one where the problem you are investigating has not happened. So use docker exec to look and to confirm, then make the fix in the image or in the command that starts the container, where it survives the next start.