To access a Docker container’s shell, use the docker exec
command with the -it
flags (interactive terminal). Here’s how:
1. Access Shell in a Running Container
docker exec -it <container_name_or_id> /bin/sh
# or (if Bash is available)
docker exec -it <container_name_or_id> /bin/bash
Example:
docker exec -it my_nginx_container /bin/bash
2. Find the Container Name/ID
List running containers to identify your target:
docker ps
# Output:
# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
# a1b2c3d4e5f6 nginx:latest "/docker-entrypoint.…" 2 hours ago Up 2 hours 80/tcp my_nginx_container
3. If the Container Isn’t Running
Start the container first (if stopped):
docker start <container_name_or_id>
4. Start a New Container with Shell Access
If you need to start a new container and immediately access its shell:
docker run -it --name my_temp_container <image_name> /bin/sh
# Example:
docker run -it --rm alpine /bin/sh # Uses Alpine's `sh` shell
5. Common Shell Paths
- Alpine-based images:
/bin/sh
(usesash
shell) - Debian/Ubuntu-based images:
/bin/bash
- If unsure: Check the image documentation or use
ls /bin/*sh
.
Troubleshooting
- “No such file or directory”: The shell (e.g.,
/bin/bash
) isn’t installed in the container. Use/bin/sh
or modify the image to include a shell. - Override the entrypoint (if the default blocks shell access):
docker exec -it --entrypoint /bin/sh <container_name>
Key Notes
- Use
Ctrl+D
or typeexit
to leave the shell. - The
--rm
flag indocker run
automatically removes the container when you exit. - For minimal images (e.g.,
scratch
), a shell may not exist—modify the Dockerfile to include one.