DOCKER - 13 Have a Shell in a Container
In this lesson we step inside a container to manipulate it from the inside. Looking at containers from the outside is convenient, but sometimes you need a live shell. Docker gives us several commands for that: docker container run -it to start a new container with an interactive terminal, and docker container exec to attach a shell to a container that is already running.
Opening a shell with docker container run
The -it flag combines --interactive and --tty to give us an interactive terminal. After the image name we override the default command — here we ask for bash:
docker container run -it --name proxy nginx bash
The prompt switches to root@<container-id> — you are root inside the container, not on the host. From there ls -al, package installs and configuration tweaks are all fair game. When you type exit, the container stops, because a container only lives as long as its main command. Since we replaced nginx with bash, leaving bash terminates the container. The same trick with Ubuntu shows how minimal a container image is: apt-get update && apt-get install -y curl is needed even to get a tool like curl. To re-enter an existing stopped container, use docker container start -ai <name>.
exec into a running container
When a container is already running something useful (MySQL, Nginx), we don't want to replace its main process. Use exec to spawn an extra one alongside it:
docker container exec -it mysql bash
This launches a second process inside the running MySQL container without affecting mysqld. Exit the bash and the MySQL container keeps running normally — that's exactly the behaviour you want for administrative tasks.
- nginx / ubuntu — full bash available out of the box
- alpine — only ~5 MB, no bash, use
shinstead apk— Alpine's package manager (you canapk add bashif you really need it)
Alpine is a great example of how stripped-down images can be: docker container run -it alpine bash fails with "bash not found" because the image doesn't ship bash at all. Switching the command to sh works. The takeaway: you can only run programs that exist inside the image, so always check what shells and tools are present before exec-ing in.