Running A Cronjob Inside Docker Container In 5 Steps

by Nivesh Goyal, DevOps Engineer, Devtron

In this blog, we will discuss and understand the steps on how to set a Cron job inside the container.

Prerequisites:

  • Docker should be installed on your system.
  • You should have an account on GitHub.

What is a Cron job?

Cron is a job scheduler. A cron job is a command used for scheduling tasks to be executed automatically after a specific time period. Mostly cron jobs are used for executing scripts, taking backup of files, etc.

Steps to run cron job inside a container:

  1. Create a script file(task file)
  2. Create a cron job file
  3. Create a docker file
  4. Create a docker image from the docker file
  5. Run the docker image inside the container

Create a script file:

First, create a script file as per your requirement, which commands or tasks you have to run, and save it into the “.sh” file. Here, I have created a script. sh file:

!/bin/bash
touch/var/log/cron.log
crontab/etc/cron.d/container_cronjob
  1. Create a cron job file:

Now create a cron file and write cron job details inside the file, like when you want to run your task. Below is the sample cron file; in this, the script is running every minute.

NOTE:

An empty line is required in the cron job file at the end of the file for a valid cron file.

  1. Create a docker file:

Finally, create a docker file and build your docker image. Below is a sample Dockerfile.

NOTE:

Put the cron job file and script file inside the same directory in your code repository where you are keeping your Dockerfile.

  1. Create a Docker Image:

Now run the following command to build the Dockerfile. You can change the tag as per your need:

  1. Run the docker image inside the container:

Now Spin up a container using the above image, run the following command:

Note:

If you want to check, your cron is running or not, run the below command from outside the container:

That’s all about how you can run a cron job inside a Docker container. If you want to deploy it inside the Kubernetes cluster using Devtron’s CI/CD tool, follow this blog.

Devtron is redefining the paradigm of how #DevOps should be done. It automates #ReleaseOrchestration & Life Cycle Management of Applications on #Kubernetes.