Search code examples
phpdockercroncommand-line-interface

Run PHP script with Docker container


I have a setup with docker-compose using nginx with php7-fpm. This is running and my PHP page is working fine. Now I need to execute some php scripts in a Cron Job, but I do not want to install php on the host machine, where I plan to install the Cron Jobs.

How can I run the php scripts using the php7-fpm docker container?

On my old system I had installed php7 so I could setup a cron task like this:

0 2 * * * /usr/bin/php /var/www/page/cron/my_php_script.php >> /var/log/cron.log 2>&1


Solution

  • There are a couple of ways, but I will do it navigating to the folder of the project and executing docker-compose exec. Example:

    0 2 * * *   cd /my/project/folder && docker-compose exec -T php-fpm-container php -f /my/project/folder-inside-container/cron/my_php_script.php >> /var/log/cron.log 2>&1
    

    Some important points to here:

    1. There should be a docker-compose.yml with the environment you setted up (if not you can use the flag -f to point to the docker-compose file)
    2. php-fpm-container should be the name of your service/container with the php-fpm installation
    3. If you want to pipe the logs to a file the folder should be mounted so you can access it from outside the container. Or you can pipe output to /dev/stdout so it can be accessed by docker-compose logs command.