The docker exec
command serves for executing commands in a running container.
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 commands Docker containers.
Cool Tip: Enter a running Docker container and start a bash
session! Read More →
Run Command in Docker Container
Use the docker exec
to execute a command in already running Docker container:
$ docker exec -it <container> <command>
– example –
$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES df51f67134f2 nginx:latest "/docker-e..." 5 mins ago Up 5 min 80/tcp nginx $ docker exec -it 067f66a99dff nginx -v nginx version: nginx/1.17.10
If the required Docker container is stopped, you should firstly start it from an image using the docker run
command:
$ docker run -dt <image> $ docker exec -it <container> <command>
– example –
$ docker run -dt alpine:latest c7d42807e9c083f3cf88fea7ec476ad86525ac2b9dfc816fd75bfb150d4c8920 $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c7d42807e9c0 alpine:latest "/bin/sh" 1 sec ago Up 1 sec alpine $ docker exec -it c7d42807e9c0 cat /etc/alpine-release 3.11.6
Option | Description |
---|---|
-i , --interactive |
Keep STDIN open even if not attached |
-t , --tty |
Allocate a pseudo-TTY |
-d , --detach |
Run the container in the background (detached mode) |
Cool Tip: Copy files between Docker container and a host machine! Read More →