dockerdocker-composecrondockerfiledjango-cron

Docker configure CRON JOB in python-alpine


I've created a simple Django application, and I want to set up a cron job. I'm using django-cron package.

I tried 2 approaches, the first one without docker-compose, I used this approach, but then I realised it wasn't working as the alpine shell was BusyBox, and it didn't have the necessary commands.

Then for the second way, I commented out a few commands in Dockerfile and followed the approach shown in this repository.

I've tried literally everything over 3 days, but every approach has some problems that cannot be FIXED.

Keeping following things in mind -

Dockerfile file

# syntax=docker/dockerfile:1
FROM python:3.10.2-alpine

ENV PYTHONUNBUFFERED=1

WORKDIR /usr/src/app

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

# Creating DB Tables
RUN python manage.py makemigrations
RUN python manage.py migrate

# Configuring CRONJOB
COPY bashscript /bin/bashscript
# COPY cronjob /var/spool/cron/crontabs/root
# RUN chmod +x /bin/bashscript
# RUN crond -l 2 -b                  # THIS ISN'T WORKING FOR IDK WHAT REASON

RUN python manage.py collectstatic --noinput

EXPOSE 8000

CMD [ "python", "manage.py", "runserver", "0.0.0.0:8000" ]

docker-compose.yml file

version: "3.9"

services:
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
  mycron:
    build: .
    volumes:
      - .:/code
    entrypoint: sh /usr/src/app/crontab.sh

crontab.sh file

#!/usr/bin/env bash

# Ensure the log file exists
touch /var/log/crontab.log

# Ensure permission on the command
chmod a+x /bin/bashscript

# Added a cronjob in a new crontab
echo "*/1 * * * * python manage.py runcrons >> /var/log/crontab.log 2>&1" > /etc/crontab

# Registering the new crontab
crontab /etc/crontab

# Starting the cron
/usr/sbin/service cron start   # CAN'T USE THIS BECAUSE service is not a command

# Displaying logs
# Useful when executing docker-compose logs mycron
tail -f /var/log/crontab.log

bashscript file

#!/bin/sh
python manage.py runcrons # THIS IS THE COMMAND I WANT TO EXECUTE EVERY nth MINUTES

cronjob file

# do daily/weekly/monthly maintenance
# min   hour    day     month   weekday command
*/1     *       *       *       *       /bin/bashscript

Solution

  • You want to run a script in a container but the cronjob doesn't need to be configured in the container itself.

    You can create a script in the container to do whatever you want. And, in the server, schedule the cronjob to execute a docker exec command that runs the script in the container. Solved.