How do you open a shell inside a running Docker container?

Docker · Container Management · updated 2026-08-23

docker exec -it [ID] bash — Enter container

Run docker exec -it [ID] bash, replacing [ID] with the container ID or name from docker ps. The -it flags keep the session interactive; use sh instead of bash for minimal images that do not ship bash.

The -it pair matters: -i keeps stdin open and -t allocates a pseudo-terminal, and without both you get a shell that either exits instantly or cannot echo what you type. If bash is not found, the image is likely minimal (Alpine-based) - retry with sh, which busybox always provides.

exec attaches to a running container; if the container is stopped, docker run -it image sh starts a fresh one instead. For a one-off command you do not need a shell at all - docker exec container ls /app runs it directly.

Related Docker shortcuts: Container Management

ShortcutActionNotes
docker run [image]Run containerCreate and start a new container.
docker psList runningList currently running containers.
docker ps -aList allList all containers including stopped.
docker stop [ID]Stop containerStop a running container.
docker rm [ID]Remove containerRemove a stopped container.
docker exec -it [ID] bashEnter containerOpen a bash shell inside a running container.
docker logs [ID]View logsView container logs.
docker restart [ID]RestartRestart a container.

From the Docker reference (24 entries) · all how-to answers

When bash is not there

Minimal images (Alpine, distroless, scratch-based) often lack bash; the error is "executable file not found". Try sh, and if that fails too the image has no shell at all — distroless images are like this by design. For those, docker debug (Docker Desktop) or a temporary sidecar with a shell sharing the container's namespaces is the way in. docker exec -it [ID] bash -c "cmd" runs a single command when a full session is not needed.

Users, environment and working directory

exec starts the shell as the image's configured user and in its WORKDIR, with the container's environment. -u root gives a root shell in a container that runs as a non-root user (useful for installing a debugging tool), and -w /app sets the directory. Changes made in the shell — files, packages — live only in that container's writable layer and vanish when it is recreated.

exec versus attach and run

docker attach connects to the container's main process rather than starting a new one, so Ctrl + C may stop the application; exec is almost always what you want. docker run -it image bash starts a fresh container from the image with a shell as its main process, which is the way to inspect an image before it runs as a service.