How to Build a Docker Image For Running a Cron Job
In automation world there are many ways to automate a task and in most cases the automation need scheduler function. You might need to automate a simple scheduled task such as sending a periodic email or something more complicated such as buying or selling cryptocurrencies based on 200 days of bitcoin moving average.
Cron job is the simplest and easiest way to schedule a task. In certain cases you might want to have a container that runs a cron service to execute some tasks. This article is exactly about that 😁. Let’s dive deeper.
I use a python image as base where you can execute your python code, but there will be no python code in this example. You need to replace few things from following Dockerfile code.
- You need to replace cool_task.cron with your cron file
RUN apt-get update -y \
&& apt-get install cron -y
COPY cool_task.cron /etc/cron.d/cool_task.cron
RUN chmod 0644 /etc/cron.d/cool_task.cron \
&& crontab /etc/cron.d/cool_task.cron
CMD ["cron", "-f"]
An example of cron file that executes a shell script file buy_bitcoin.sh every 2 minutes
*/2 * * * * bash /buy_bitcoin.sh >> ~/cron.log 2>&1
Building the image
sudo docker build . -t your_repo/py-cron:latest
You need to replace several things from this example:
- You need to specify your volume mount (if required)
sudo docker-compose up -d
Enjoy your new scheduler in a Docker container!