- cron
- cron -f
- -d
Docker with crontab
In order to set up a so-called cron-job you need to edit or install the crontab file in the Docker image and then you need to tell your Docker image to start it when the container starts and to just keep waiting for it to work. So not to quit.
First we prepare a file that looks like a crontab file. We won't go into the details of the crontab format, you can read about it in the linked Wikipedia entry. Suffice to say the 5 stars tell the cron service to run the job every minute.
The job itself is not very interesting. It runs the "date" command and redirects the output to a file called /opt/dates.txt appending to it every time. We only use this to see that the cronjob indeed works.
examples/crontab/crontab.txt
* * * * * date >> /opt/dates.txt
examples/crontab/Dockerfile
FROM ubuntu:23.04 RUN apt-get update && \ apt-get install -y cron COPY crontab.txt /opt RUN crontab /opt/crontab.txt CMD ["cron", "-f"]
docker build -t mydocker .
docker run -d --rm --name chronos mydocker
Meaning that the cron-job worked as expected.
docker container cp chronos:/opt/dates.txt .
docker container stop chronos