Docker: Run Multiple Commands in Container

Multiple commands can be executed in a running Docker container using the docker exec command.

If the Docker container is stopped, before running the docker exec command it should be started using the docker run command.

In this short note i will show the examples of how to execute multiple commands in a Docker container.

Cool Tip: Run command in a Docker container! Read More →

Run Multiple Commands in Docker Container

Use the followig syntax to run multiple commands in a running Docker container:

$ docker exec -it <container> <bash|sh> -c "<command1>; <command2>; <command3>"

– example –

$ docker exec -it c7d42807e9c0 /bin/sh -c "whoami; cat /etc/alpine-release"
root
3.11.6

To execute the next command only if the previous one has completed successfully (0 exit code) – split multiple command to run using && delimiter:

$ docker exec -it <container> <bash|sh> -c "<command1> && <command2> && <command3>"

– example –

$ docker exec -it 89fa2ac009bb /bin/bash -c "nginx -t && nginx -s reload"
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
2020/06/08 18:34:59 [notice] 78#78: signal process started

In the example above, nginx will be reloaded only if configtest is successful.

As has already been mentioned, the docker exec command can be applied to a running container only.

If the required Docker container is stopped, you should firstly start it from an image using the docker run command:

$ docker run -dt <image>

Cool Tip: Enter a running Docker container and start a bash session! Read More →