Docker Run
docker run
creates a new container from an image. If run without the -d
flag, the container will stop when interrupted. For example, if we run Redis v6.0.9 like this
docker run redis:6.0.9
We will get an output similar to:
1:C 11 Jan 2021 08:58:21.487 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
1:C 11 Jan 2021 08:58:21.487 # Redis version=6.0.9, bits=64, commit=00000000, modified=0, pid=1, just started
1:C 11 Jan 2021 08:58:21.487 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
...
Interrupting the process with ctrl-c will stop the container. If instead, we run it in detached mode
like this
docker run -d redis:6.0.9
# Output
# ab2801c33d558b62d870f809f8a47673459da9b6ae52632f5bfb0ed72094227a
We will only get the container id as output. We will need to explicitly stop the container using docker stop <id>
docker stop ab2801c33d558b62d870f809f8a47673459da9b6ae52632f5bfb0ed72094227a
When To Use Docker Run
- When you want to create a new container from an image.
- When you need a container to run in the background
- When you want a one-time container that can be stopped with ctrl-c
Docker Exec
Docker exec is useful for starting processes or running commands on already running containers. Using our Redis example, we may need to execute some commands on the CLI. So we will use docker exec to run the standard CLI.
docker exec -it ab2801c33d558b62d870f809f8a47673459da9b6ae52632f5bfb0ed72094227a redis-cli
This should give us the prompt
127.0.0.1:6379>
When To Use Docker Exec
- When a command needs to be executed
- When a shell from a container needs to be invoked
Wrap Up
If you learned something from this tutorial, consider subscribing to my zero spam newsletter at the top of the post. Thanks for reading. Adios βπΎπ§‘.