Scheduling

DevOps Docker Scheduling

Create crontab scheduling on the docker

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

# use the bin/bash as the default environment
* * * * * echo "Hello, world!111" >> /var/log/cron.log 2>&1
* * * * * echo "Hello, world!222" >> /dev/null 2>&1

# If your docker doesn't use the bin/bash as the default environment
* * * * * /bin/bash -l -c 'cd /my/laravel/app/ && php artisan schedule:run >> /dev/null 2>&1'

Install cron application on docker container

FROM ubuntu:latest

RUN apt-get update && apt-get -y install 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

# Update the crontab file permission
RUN chmod 0644 /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 laravel.cron.Dockerfile

# cronjob.Dockerfile
FROM ubuntu:latest

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

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

# Update the crontab file permission
RUN chmod 0644 /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: cronjob
    build: cronjob.Dockerfile
    image: cronjob:v1.0
    volumes:
      - /home/KJ/app:/my/app/
    restart: always
docker-compose up -d cronjob

Troubleshooting

/bin/sh: 1: not found

To make sure that the command is run in the /bin/bash environment, you can modify your cron job to explicitly load the Bash environment before running the command.

# my_docker_crontab
# m h  dom mon dow   command
* * * * * /bin/bash -l -c 'php /path/to/your/script.php'

This will tell cron to run the command in a login shell (-l option), which will load the Bash environment, including any environment variables and aliases that you may have defined.

The -c option is used to specify the command to run. In this case, we’re running the php command with the path to your script as an argument.

Reference