Run Short-Lived Docker Containers

Mark Shust
InstructorMark Shust
Share this video with your friends

Social Share Links

Send Tweet

Learn the benefits of running one-off, short-lived Docker containers. Short-Lived containers are useful to execute one-line commands or setup scheduled tasks. We'll demonstrate setting up a cronjob from the host machine to tap into the benefits of running automated, timed scripts with Docker.

[00:00] You will typically run docker containers as background daemons by specifying the -d flag. This keeps the container running in the background until it is terminated. However, sometimes you want to execute just a single command either to test something out or to execute a short lived task.

[00:16] We can do this with --rm flag. Since docker containers only run as long as the specific command is active, the container will be removed immediately when the running command has completed.

[00:27] We can see the actively run in command here "nginx -g 'daemon off." What if we don't know what the nginx -g flag does? Probably you want to do some research into the nginx help documentation.

[00:39] We can do this by typing "docker run --rm nginx," and then the command which is "nginx -h." What just happened when you ran this command is that docker created the container, ran the command when we passed it, and then immediately terminated it and removed the container all in under a second.

[00:59] It's possible to run worker jobs or queue task by setting up a cron job on the host server to run one of docker commands. Let's see an example. Let's type "docker run --rm debian hostname >> /tmp/containers."

[01:12] Running the hostname command within docker will print out the container's container ID. Then we append the result to the temp container's directory of our host machine. We can inspect this successfully ran by typing "cat /tmp/containers."

[01:34] We can set this up to run as a cron job on our host. Let's make this container run every minute of every day and continue to append to temp containers with a string of the container ID of our temporary one off container. If wait until the next minute and check the temp container's file, we'll see another container ID appended to the file.