0
0
Dockerdevops~5 mins

Opening a shell in container in Docker - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you need to look inside a running container to check files, run commands, or debug problems. Opening a shell inside the container lets you do this easily.
When you want to check the contents of files inside a running container.
When you need to run commands manually inside the container for debugging.
When you want to inspect environment variables or running processes inside the container.
When you want to test changes inside the container before updating the image.
When you want to troubleshoot why an application inside the container is not working.
Commands
This command lists all running containers so you can find the container ID or name to open a shell inside.
Terminal
docker ps
Expected OutputExpected
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES b7c8f9a1d2e3 nginx:1.23.3 "/docker-entrypoint.…" 2 minutes ago Up 2 minutes 0.0.0.0:8080->80/tcp my-nginx
This command opens an interactive shell inside the running container named 'my-nginx'. The '-it' flags allow you to interact with the shell.
Terminal
docker exec -it my-nginx /bin/sh
Expected OutputExpected
#
-i - Keep STDIN open so you can type commands
-t - Allocate a pseudo-TTY so the shell works interactively
This command exits the shell inside the container and returns you to your host terminal.
Terminal
exit
Expected OutputExpected
No output (command runs silently)
Key Concept

If you remember nothing else from this pattern, remember: use 'docker exec -it <container_name> /bin/sh' to open an interactive shell inside a running container.

Common Mistakes
Trying to open a shell in a container that is not running.
The 'docker exec' command only works on running containers, so it will fail if the container is stopped.
First run 'docker ps' to confirm the container is running, or start it with 'docker start <container_name>' before opening a shell.
Using '/bin/bash' in containers that only have '/bin/sh'.
Some lightweight containers like 'nginx' do not have bash installed, so the shell command fails.
Use '/bin/sh' which is more commonly available in minimal containers.
Omitting the '-it' flags when running 'docker exec'.
Without '-it', the shell is not interactive and you cannot type commands inside the container.
Always include '-it' to open an interactive terminal session.
Summary
Use 'docker ps' to find the running container's name or ID.
Run 'docker exec -it <container_name> /bin/sh' to open an interactive shell inside the container.
Type 'exit' to leave the container shell and return to your host terminal.