How to Enter a Running Docker Container Easily
To enter a running Docker container, use the
docker exec -it <container_name_or_id> /bin/bash command to open an interactive shell inside it. Alternatively, docker attach <container_name_or_id> connects you to the container's main process console.Syntax
There are two main commands to enter a running container:
- docker exec -it <container> <command>: Runs a new command inside the container interactively.
- docker attach <container>: Connects your terminal to the container's main process.
Here, -i keeps input open, -t allocates a terminal, and <container> is the container's name or ID.
bash
docker exec -it <container_name_or_id> /bin/bash docker attach <container_name_or_id>
Example
This example shows how to start a container and enter it using docker exec to get a bash shell.
bash
docker run -d --name mycontainer ubuntu sleep 300 docker exec -it mycontainer /bin/bash # Inside the container shell, you can run commands like 'ls' or 'pwd'.
Output
Unable to show interactive shell output here, but after running the commands, you will be inside the container's bash shell prompt.
Common Pitfalls
- Trying to enter a container without
-itflags will not give an interactive shell. - Using
docker attachcan be confusing because it connects to the main process and may not provide a shell. - Some containers may not have
/bin/bash; use/bin/shinstead.
bash
docker exec mycontainer /bin/bash # Wrong: missing -it flags docker exec -it mycontainer /bin/bash # Correct: interactive shell
Quick Reference
| Command | Description |
|---|---|
| docker exec -it | Open interactive bash shell inside container |
| docker exec -it | Open interactive sh shell if bash is unavailable |
| docker attach | Attach to container's main process console |
| docker ps | List running containers to find container name or ID |
Key Takeaways
Use 'docker exec -it /bin/bash' to enter a running container interactively.
If bash is missing, try 'docker exec -it /bin/sh' instead.
'docker attach' connects to the main process but may not provide a shell.
Always include '-it' flags for interactive terminal access.
Use 'docker ps' to find the container name or ID before entering.