Thursday, October 6, 2022

[SOLVED] Docker - Call PHP script on web container from a CRON container

Issue

I have a web app running in a docker container (apache, php). I've been looking for solutions to install a cron job in order to regularly perform some actions on my web app (execute php files etc).

I found multiple answers (How to run a cron job inside a docker container?), all based on creating a separated container which will be responsible to run the cron jobs.

Now, how do I make this cron container communicate with my web container ?

I found multiple solutions :

  • Install and use CURL on my cron container
  • Install cron on web container and run it in the background (against good practices)
  • I'm also wondering if I could use a shared network in my compose file between my web and my cron container, but I'm unsure on how to make it work.

Do you guys have other ideas or code samples to help me achieve this ?


Solution

Managed to make it work using a shared network between my web container and my cron container (thanks @David Maze)

Cron Dockerfile :

FROM ubuntu:18.04

RUN apt-get update
RUN apt-get install -y systemd
RUN apt-get install -y nano
RUN apt-get install -y cron
RUN apt-get install -y curl
 
RUN systemctl enable cron
RUN (crontab -l -u root; echo "* * * * * curl web:80 -d 'action=cron.run'") | crontab

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

# Run the command on container startup
CMD cron && tail -f /var/log/cron.log

Docker compose

version: '3.7'

services:

    # Web container
    web:
        # [...]
        ports:
            - "0001:80"
            - "0002:443"
        networks:
            - cron_network

    # Cron container
    cron:
        # [...]
        depends_on:
            - web
        networks:
          - cron_network

networks:
  cron_network:


Answered By - Cephou
Answer Checked By - Katrina (WPSolving Volunteer)