How to start a bash shell in a Docker container? (Enter container docker)

How to run a container and execute BASH Shell?

To start a container and run the default bash shell, you can use.

docker run -it ubuntu

Example output:

dev@codetryout:~$ docker run -it ubuntu
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
6b851dcae6ca: Pull complete
Digest: sha256:6120be6a2b7ce665d0cbddc3ce6eae60fe94637c6a66985312d1f02f63cc0bcd
Status: Downloaded newer image for ubuntu:latest
root@4f95e673d576:/# echo $SHELL
/bin/bash
root@4f95e673d576:/#

Running bash on a running container from the host

You can use the docker exec command to bash into a Docker container. Replace with the name or ID of the container you want to access. Here’s an example command that demonstrates how to bash into a running container id “4f95e673d576”:

docker exec -it my-container bash

Example response:

dev@codetryout:~$ docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS         PORTS     NAMES
4f95e673d576   ubuntu    "/bin/bash"   2 minutes ago   Up 2 minutes             intelligent_euclid

dev@codetryout:~$

dev@codetryout:~$ docker exec -it 4f95e673d576 bash
root@4f95e673d576:/#
root@4f95e673d576:/#

It’s worth noting that the availability of the bash shell within the container depends on the base image used to create the container. If the image doesn’t have bash installed, you may need to use an alternative shell, such as sh, ash, or zsh, depending on what’s available in the container’s filesystem.