Georg Leber
Georg Leber

Reputation: 3580

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

Upvotes: 2

Views: 4807

Answers (2)

salpreh
salpreh

Reputation: 345

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.

Upvotes: 3

Felix G
Felix G

Reputation: 861

You might want to rebuild your docker-container according to your requirements & add crontab to inside the container if you're planning on using it more.

Alternatively, you can use dockers exec command, this allows you to execute a command inside a specified container. Your crontab could run the docker exec with your PHP-Command.

Upvotes: 1

Related Questions