ryanwhocodes Feb 17, 2018 · 2 min read

Run bash or any command in a Docker container

A beginners guide to running bash and other commands in Docker containers.

Once you’ve defined your images and Dockerfiles, you then may want to enter a container to run bash or other commands. There are a few different ways to do this depending on whether you are using docker or docker-compose.

Either use docker run to create a container and run the command in it, or use docker exec to run a command in an existing container.

Contents

Docker

Assuming you know the name of your container, or if you don’t run docker ps to list the processes running and copy the container name…

Use either docker run or use docker exec with the -i (interactive) flag to keep stdin open and -t to allocate a terminal.

docker exec -i -t container_name /bin/bash

Or to run one or many commands:

docker exec -ti my_container sh -c "echo a && echo b"

Meanwhile, in the world of docker-compose

Docker Compose

The equivalent commands docker-compose run and docker-compose exec automatically assign a terminal so you can just run the following to get an interactive prompt:

docker-compose exec <container name> sh

The same structure applies to running any command:

docker-compose exec <container name> <command>

To run a string of commands together, they must be connected to a shell. For example:

docker-compose exec  <container name> sh -c '<command 1> && <command 2> && <command 3>'

Find out more

Now you should be able to use command line instructions within docker containers. For example you can navigate file structures, view files, copy or replace files within the container — very helpful for debugging or customising configuration files.