0
0
DockerHow-ToBeginner · 3 min read

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 -it flags will not give an interactive shell.
  • Using docker attach can be confusing because it connects to the main process and may not provide a shell.
  • Some containers may not have /bin/bash; use /bin/sh instead.
bash
docker exec mycontainer /bin/bash  # Wrong: missing -it flags

docker exec -it mycontainer /bin/bash  # Correct: interactive shell
📊

Quick Reference

CommandDescription
docker exec -it /bin/bashOpen interactive bash shell inside container
docker exec -it /bin/shOpen interactive sh shell if bash is unavailable
docker attach Attach to container's main process console
docker psList 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.