In this short article, I will show how to run scheduled cron jobs in Laravel for an application that is deployed in a Docker container. The most proper way would be to run cron directly in a separate container and process that job there. But this will increase the load on the system and resource consumption. There is another option that looks acceptable.
You can run Supervisor process manager in the container and use it to run schedule:work commands to process scheduled tasks and queue:work for the queue. But it still requires a separate container.
But there is a less proper way that also works. You can add the schedule:run command to the system cron of the Docker host. It will make transferring the application to another server more difficult, but it will work very well.
For example, let’s add cron handling for an application that is located in the /home/apps/ folder and mounted in the phpfpm81 container to /var/www:
* * * * * cd /home/haait/app/ && /usr/bin/docker-compose exec -T docker-phpfpm81 bash -c "cd /var/www/ && php artisan schedule:run" > /dev/null 2>&1
In the newest versions of Docker the compose plugin is built-in, so the command will look like this:
* * * * * cd /home/haait/app/ && /usr/bin/docker compose exec -T docker-phpfpm81 bash -c "cd /var/www/ && php artisan schedule:run" > /dev/null 2>&1
The -T option is required to disable the interactive binding of the container to your TTY device. Otherwise, you will get the error with the message “docker-compose exec: the input device is not a TTY”. Also, note that the path to the docker or docker-compose binary must be absolute.