Learn the differences between the Docker CLI
Use this to run a command in a new container. It suits the situation where you do not have a container running, and you want to create one, start it and then run a process on it.
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Following the docker run command, you must specify the image to create the container from, but there are optional arguments you can pass as well.
docker run --name ubuntu_bash --rm -i -t ubuntu bash
This will create a container named
ubuntu_bash and start a Bash session. A more detailed breakdown of the options and arguments used in the example is:
--nameassigns a name to the container, in this case
--rmis like the bash command
rmit removes the container, but when it exits
-iis short for
-interactive, this ensures
STDINis kept open even if not attached to the running container
-t, which can also be referenced with
-tty, starts an interactive bash shell in the container
The image for the container follows the options, here it is the image
The last part that follows the image, is the command you want to run:
This is for when you want to run a command in an existing container. This is better if you already have a container running and want to change it or obtain something from it. For example, if you are using Docker Compose you will probably spin-up multiple containers and you may want to access one or more of them once they are created.
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
exec also has a range of options and arguments you can specify, although you must state the container and command to execute. You can start an interactive bash shell on a container named
docker exec -it ubuntu_bash bash
Here the options
-it have the same effect as with run. An example with more options and arguments is:
docker exec -d -w /temp ubuntu_bash touch my_file.sh
-wfollowed by the directory or file path allows you to state which working directory you want to run the command in.
-detachedmeans that the container will run in detached mode, so you can still continue to use your terminal session with the container running in the background. Don’t use this if you want to see what the container sends to
The command is touch used to create the file with the name
/tempdirectory of the running container ubuntu_bash
Find out more
Aside from these two commands, there are other Docker commands that have subtle differences, such as run’s similarities to build, create. Learning more and trying out the different docker commands can help you become a pro at using this powerful cloud technology. Check out the Docker docs and my other posts for more.
Originally published at medium.freecodecamp.org.