Connect with us


How to build a Docker cron job Container easily [2023]

In this tutorial, we’ll be setting up Cron jobs in Docker and discuss how to avoid a common pitfall.

Let’s Code It!

We’ll build a docker cron job that runs while other services on docker are running. This is particularly useful if we want to backup our databases.

Setting things up

Directory structure.

Create a docker-cron root directory.

Container #1: Node

To start we’ll setup a node image that will act as a service that’s supposed to run while the cron job is running.

Generate a blank node app in docker-cron:

Create a Dockerfile in the node-app directory:

 Common Pitfall

Running cron in the same container as a service.

The Docker ubuntu image by default doesn’t run cron at runtime because it’s intended to run only one process at a time. Below is improperly attempting to run two processes simultaneously, something Docker doesn’t support:

The trick is splitting cron into its own separate container.

Container #2: Cron

We’ll setup an ubuntu image that will run our cron job in a separate container. This image doesn’t come with cron by default, so we’ll need to install it and do a general update. Create a cron-app directory in the docker-cron project folder.

Create mycron in cron-app that specifies your cron:

Make sure you have a blank line at the end of mycron

This cron will run every minute.

Create in cron-app that specifies what your cron does:

Create a Dockerfile in the cron-app directory with the following contents:

Docker Compose

Now we’ll bring the two images together with Docker Compose.

Create a docker-compose.yml file in the root docker-cron directory with the following contents:

Thank you for taking the time to read this tutorial. Check out our previous article about docker add vs copy. Also, Your feedback will be appreciated.

Continue Reading
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *