Docker Tip #40: Running Cron Jobs on the Host vs. in a Container
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.
We have a couple of options here to run an automated task on a schedule:
- Use the Docker host’s version of cron
- Create a new container and run cron inside of that
- 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.