How can I run bash in a docker container?

If you docker run without attaching a tty, and only call bash, then bash finds nothing to do, and it exits. That’s because by default, a container is non-interactive, and a shell that runs in non-interactive mode expects a script to run. Absent that, it will exit.

To run a disposable new container, you can simply attach a tty and standard input:

docker run --rm -it --entrypoint bash <image-name-or-id>

Or to prevent the above container from being disposed, run it without --rm.

Or to enter a running container, use exec instead:

docker exec -it <container-name-or-id> bash

In comments you asked

Do you know what is the difference between this and docker run -it --entrypoint bash docker/whalesay?

In the two commands above, you are specifying bash as the CMD. In this command, you are specifying bash as the ENTRYPOINT.

Every container is run using a combination of ENTRYPOINT and CMD. If you (or the image) does not specify ENTRYPOINT, the default entrypoint is /bin/sh -c.

So in the earlier two commands, if you run bash as the CMD, and the default ENTRYPOINT is used, then the container will be run using

/bin/sh -c bash

If you specify --entrypoint bash, then instead it runs

bash <command>

Where <command> is the CMD specified in the image (if any is specified).

Leave a Comment