Featured image of post docker crontab for scheduling running program

docker crontab for scheduling running program

We will need to schedule our task for running program on the specific time, and scheduling our program tasks by using docker

We will build the specific environment for running our projects in docker. Such as using PHP, Python, Golang. But sometimes we need to run the specific tasks at a specific time regularly and automatically. We will use crontab to achieve our goal. But what if we want to get the same result on docker? Here is the example by using PHP.

Create custom crontab file

Create the custom crontab file in the project that names my_docker_crontab

# my_docker_crontab
# m h  dom mon dow   command
* * * * * /app/job.php

Install cron application on docker

Docker images is minimize unit for specific usage without cron. So it should be install by yourself on our specific environment in docker. And scheduling to run tasks that we want to do.

RUN apt-get update && apt-get install -y cron

Add custom crontab file

We will copy the custom crontab file my_docker_crontab to docker images. and specify crontab to run this tasks scheduling.

# Add docker custom crontab
ADD my_docker_crontab /etc/cron.d/my_docker_crontab

# Specify crontab file for running
RUN crontab /etc/cron.d/my_docker_crontab

Executing crontab

Finally, we will execute command cron -f to execute our cron tasks every minutes.

# execute crontab
CMD ["cron", "-f"]

Here is the full version of the crontab Dockerfile

FROM php:7.4-fpm
WORKDIR /var
RUN apt-get update && apt-get install -y cron libpq-dev libpng-dev libzip-dev zip
RUN docker-php-ext-install pgsql pdo_pgsql gd zip\
&& docker-php-ext-enable opcache

# Add docker custom crontab
ADD my_docker_crontab /etc/cron.d/my_docker_crontab

# Specify crontab file for running
RUN crontab /etc/cron.d/my_docker_crontab

# execute crontab
CMD ["cron", "-f"]

Run docker-compose

We will set the setting in docker-compose.yml to run our Dockerfile. And execute docker-compose up -d to running this cronjob container in background

# docker-compose.yml
version: '3'

services:
  cronjob:
    container_name: docker_php_cronjob
    build: .
    image: docker_php_cronjob:v1.0
    volumes:
      - /web/app/:/app
    restart: always
docker-compose up -d

Reference

Donate KJ 贊助作者喝咖啡

如果這篇文章對你有幫助的話,可以透過下面支付方式贊助作者喝咖啡,如果有什麼建議或想說的話可以贊助並留言給我
If this article has been helpful to you, you can support the author by treating them to a coffee through the payment options below. If you have any suggestions or comments, feel free to sponsor and leave a message for me!
方式 Method 贊助 Donate
PayPal https://paypal.me/kejyun
綠界 ECPay https://p.ecpay.com.tw/AC218F1
歐付寶 OPay https://payment.opay.tw/Broadcaster/Donate/BD2BD896029F2155041C8C8FAED3A6F8
All rights reserved,未經允許不得隨意轉載
Built with Hugo
Theme Stack designed by Jimmy