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

comments powered by Disqus
All rights reserved,未經允許不得隨意轉載
Built with Hugo
Theme Stack designed by Jimmy