Cron in Docker (PHP)

You wanna get corn running in a container? Maybe a php based container? This sucks. So let’s try to figure it out.

What I did is create a docker image as following:

FROM php:7.3-apache
USER root

# Install Cron & Sudo Package
RUN apt-get update && \
    apt-get install -y cron sudo

# OTHER STUFF GOES HERE

# Copy the script used for cron here
COPY cron_1m.sh /usr/local/bin/cron_1m.sh
COPY cron_5m.sh /usr/local/bin/cron_5m.sh

# Get it up and running
RUN chmod +x /usr/local/bin/cron_1m.sh && \
    chmod +x /usr/local/bin/cron_5m.sh && \
    echo "* * * * * sudo -u www-data /usr/local/bin/cron_1m.sh > /proc/1/fd/1 2>/proc/1/fd/1\n*/5 * * * * sudo -u www-data /usr/local/bin/cron_5m.sh > /proc/1/fd/1 2>/proc/1/fd/1" | crontab -

# Getting PHP running
WORKDIR /var/www/html
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
CMD ["www-data", "/usr/local/bin/apache2-foreground"]

The entrypoint looks like this:

#!/bin/bash

# Prepare Environment
printenv | grep -v printenv | sed -E 's;^([A-Za-z_]+)=(.*)$;export \1="\2";g' > /etc/container.env

# Change User
su $1
shift

# Exec Command
exec "$@"

And we add a cron.sh file:

#!/bin/bash

# Get environment
source /etc/container.env

# For Debuging: /bin/echo "[$(date)] Running cron (*/5)" # Or (*/1), whatever cron it is

# Get in the right place
cd /var/www/html 

# Running your script here

Now we can use this image normally to run a php container, that does php stuff under the user www-data.

For our cron job we start a second container like this:

services:
  cron:
    build:
      dockerfile: Dockerfile
      context: ./image
    restart: always
    command:
    - "root" # Don't Change to www-data
    - "/usr/sbin/cron" # Run Cron in this container
    - "-f" # Run in foreground      

Environment Variables

Environment Variables are not loaded in your cron jobs. So you have to do this in your entrypoint:

printenv | grep -v printenv | sed -E 's;^([A-Za-z_]+)=(.*)$;export \1="\2";g' > /etc/container.env

And in your cronjob add this:

source /etc/container.env


Leave a Reply

Your email address will not be published. Required fields are marked *