In this blog, we will discuss and understand the steps on how to set a Cron job inside the container.
- 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:
- Create a script file(task file)
- Create a cron job file
- Create a docker file
- Create a docker image from the docker file
- 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:
- 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.
* * * * * echo “The test cron ran at $(date)” > /proc/1/fd/1 2>/proc/1/fd/2
An empty line is required in the cron job file at the end of the file for a valid cron file.
- Create a docker file:
Finally, create a docker file and build your docker image. Below is a sample Dockerfile.
# Pulling ubuntu image with a specific tag from the docker hub.
# Adding maintainer name (Optional).
# Updating the packages and installing cron and vim editor if you later want to edit your script from inside your container.
RUN apt-get update \
&& apt-get install cron -y && apt-get install vim -y
# Crontab file copied to cron.d directory.
COPY ./files/cronjob /etc/cron.d/container_cronjob
# Script file copied into container.
COPY ./files/script.sh /script.sh
# Giving executable permission to script file.
RUN chmod +x /script.sh
# Running commands for the startup of a container.
CMD [“/bin/bash”, “-c”, “/script.sh && chmod 644 /etc/cron.d/container_cronjob && cron && tail -f /var/log/cron.log”]
Put the cron job file and script file inside the same directory in your code repository where you are keeping your Dockerfile.
- Create a Docker Image:
Now run the following command to build the Dockerfile. You can change the tag as per your need:
# docker build –tag cronjob:testing .
- Run the docker image inside the container:
Now Spin up a container using the above image, run the following command:
# docker run -itd –name container_name cronjob:testing
If you want to check, your cron is running or not, run the below command from outside the container:
# docker logs –tail 100 -f container_name
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.