Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Docker Tip #40: Running Cron Jobs on the Host vs. in a Container

docker-tips-and-tricks.jpg

Docker gives us a way to isolate processes but when it comes to cron jobs, let's run them on the Docker host when possible.

Quick Jump:
We have a couple of options here to run an automated task on a schedule:
  1. Use the Docker host’s version of cron
  2. Create a new container and run cron inside of that
  3. Install cron directly in your existing container and run 2 processes

Keep in mind, when I say cron, that could either be the traditional cron utility or a more modern systemd timer service. Both let you do the same thing.

We’re not even going to talk about #3 because that’s not a good idea.

I prefer option #1 when possible because it’s so easy to set up. If you can SSH into your server and it’s running a distro of Linux that has cron available then you’re good to go.

If you spin up a DigitalOcean server (or a server on any other major cloud provider) and install Ubuntu (or any other popular distro of Linux) you’re all set. Cron will be available to you on the Docker host. Done deal. Then you can just run whatever task you need.

I would only ever reach for #2 when the above cannot happen for whatever reasons. In that case, spinning up a container with cron in it would work. You would either bake in your cron tab file or volume mount in a cron tab file from the Docker host.

Keep in mind, if you want to automate a Dockerized task with #2, such as running docker exec postgres backup inside of your database container, then you would be responsible for configuring that cron container to be able to execute docker commands and interact with the Docker daemon running on the Docker host.

The above is too much indirection for me and that’s one reason why I prefer to use the Docker host’s version of cron whenever possible.

Free Intro to Docker Email Course

Over 5 days you'll get 1 email per day that includes video and text from the premium Dive Into Docker course. By the end of the 5 days you'll have hands on experience using Docker to serve a website.



Comments