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

2

7

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

Conchita answered 28/12, 2018 at 14:18 Comment(0)
M
9

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.

Milline answered 28/12, 2018 at 14:40 Comment(0)
F
2

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.

Fortress answered 8/5, 2022 at 13:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.