简体   繁体   中英

How to run cron jobs inside php-fpm-alpine docker container?

Hi I don't know how can I run a cron job inside this container.

I've found this: How to run a cron job inside a docker container

But that overrides the CMD, I don't know hot to keep php-fpm working

When you need to run multiple processes in your docker container a solution is to use supervisord as the main instruction. Docker will start and monitor supervisord which in turn will start your other processes.

Docker File Example:

FROM debian:9
...
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/my.conf"]

Supervisord config example (/etc/supervisor/my.conf):

[supervisord]
nodaemon=true

[program:cron]
command=/usr/sbin/crond -f -l 8
stdout_logfile=/dev/stdout
stderr_logfile=/dev/stderr
stdout_logfile_maxbytes=0
stderr_logfile_maxbytes=0
autorestart=true

[program:php-fpm]
command=docker-php-entrypoint php-fpm

Note that it is desirable to configure supervisord to output the logs to /dev/stdout and /dev/stderr to allow docker to handle these logs. Otherwise you risk your container to slow down over time as the amount of file writes increases.

The main question here is how to make PHP work kind of "in parallel" with the cron. And another answer, besides using supervisor , is to use bash's ability to manage tasks. This is generally mentioned here .
For the Alpine PHP-FPM container and the Cron , the startup script would look like this:

Docker File:

FROM php:8.1-fpm-alpine
RUN apk --update add --no-cache bash
COPY ./crontasks /var/spool/cron/crontabs/root
COPY entrypoint.bash /usr/sbin
RUN chmod a+x /usr/sbin/entrypoint.bash
ENTRYPOINT /usr/sbin/entrypoint.bash

entrypoint.bash file ( the magic is here )

#!/bin/bash
# turn on bash's job control
set -m
# Start the "main" PHP process and put it in the background
php-fpm &
# Start the helper crond process
crond
# now we bring the primary process back into the foreground
fg %1

It is important to keep in mind that the cron job syntax in Alpine is different from Debian. And different folders are used for tasks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM