Docker

How to Execute Bash Command in Docker Container?

Docker containers are an important component of Docker that offers a consistent and separated environment for running applications. However, sometimes developers may need to run bash commands in a docker container to perform tasks such as debugging, testing, or installing dependencies. In this situation, developers can utilize the “docker exec” command which allows them to execute commands in a running container.

This article will explain the method of executing bash commands in the Docker container.

How to Execute Bash Command in Docker Container?

To execute bash commands in a Docker container, try out the following steps:

Step 1: Select Running Container

First, list all Docker containers, and choose a particular running container:

docker ps

The above output has displayed two running containers and we have selected the “Cont2” container.

Step 2: Access the Selected Container

To access the selected running container for executing bash commands in it, utilize the “docker exec -it <container-name> bash” command:

docker exec -it Cont2 bash

It can be observed that the bash shell has been started and the user can now execute bash commands in it.

Step 3: Execute Bash Command in Container

Finally, execute any bash command inside the container. For instance, run the “touch <file-name>” command to create a new file in the current container:

touch demo.txt

To list all the container’s content, use the “ls” command:

ls

The above output has displayed all the container’s content including the newly created “demo.txt” file.

Conclusion

To execute bash commands in a Docker container, first, select a specific running container. Then, access it through the “docker exec -it <container-name> bash” command. Finally, execute bash commands in the Docker container. This article has explained the method of executing bash commands in the Docker container.

About the author

Laiba Younas

I have done bachelors in Computer Science. Being passionate about learning new technologies, I am interested in exploring different programming languages and sharing my experience with the world.