To access a Docker container’s shell, you can use the docker exec
or docker attach
commands. Below are the common methods:
1. Using docker exec
The docker exec
command is the most common way to open a shell session in a running Docker container. It allows you to execute a command (e.g., starting a shell) inside a container.
Steps:
- List Running Containers:
docker ps
- This shows all running containers along with their
CONTAINER ID
andNAMES
.
- This shows all running containers along with their
- Access the Container’s Shell: Use the
docker exec
command to start a shell session.- For a Bash shell:
docker exec -it <container_name_or_id> /bin/bash
- For a Shell (
sh
), if Bash is unavailable:docker exec -it <container_name_or_id> /bin/sh
- Replace
<container_name_or_id>
with the container’s name or ID.
- For a Bash shell:
- Exit the Shell: Type
exit
to leave the container shell.
2. Using docker attach
The docker attach
command allows you to interact with the container’s main process.
Steps:
- List Running Containers:
docker ps
- Attach to the Container:
docker attach <container_name_or_id>
- Detach from the Container:
- Press
Ctrl + P
and thenCtrl + Q
to detach without stopping the container. - Alternatively, use
exit
to detach and stop the container.
- Press
3. Using docker exec
with a New Terminal
If you want a new terminal session (especially useful for debugging):
docker exec -it <container_name_or_id> /bin/bash
4. For Stopped Containers
If the container is not running, you’ll need to start it first:
docker start <container_name_or_id>
Then, use one of the above methods to access the shell.
Common Errors
- Bash Not Found:
- Some minimal Docker images (like Alpine Linux) don’t have Bash installed. In such cases, use:
docker exec -it <container_name_or_id> /bin/sh
- Some minimal Docker images (like Alpine Linux) don’t have Bash installed. In such cases, use:
- Permission Denied:
- Ensure you have appropriate permissions to run Docker commands. If necessary, prefix the commands with
sudo
.
- Ensure you have appropriate permissions to run Docker commands. If necessary, prefix the commands with
Tips
- Use
docker ps -a
to list all containers, including stopped ones. - If you’re unsure about the container’s shell, try both
/bin/bash
and/bin/sh
.