Sem van den Broek
Sem van den Broek

Reputation: 113

Cron in Docker container parallel with Django

I am currently running a Django web application in a Docker compose setup on Rancher. Because I want the server to run Django management commands periodically I've setup a crontab for it.

* * * * * root /usr/local/bin/python /usr/src/app/manage.py updatesomething >> /usr/src/app/cron.log 2>&1

I am using the Dockerfile shown below and as you can see I've tried running the crontab standalone with CMD ["cron", "-f"]. This works fine and runs the command as it should. The idea however is that it can run parallel and trigger management commands on the web app. I've also verified that the crontab file is present.

The cron.log file remained empty for over 10 minutes so cron clearly is not doing its job here. Does anyone have a solution to running cron parallel in a python:3 container? Supervisor is not really an option as I have a Python 3 codebase. And I couldn't yet get Circus to work with the database in another container.

############################################################
# Dockerfile to run a Django-based web application
# Based on a Python 3 image
############################################################

# Set the base image to use to Python 3
FROM python:3

RUN apt-get update -qq && apt-get install -y -qq --force-yes cron
COPY ./docker/crontab/updatesomething /etc/cron.d/updatesomething
RUN chmod 0644 /etc/cron.d/updatesomething

RUN mkdir -p /usr/src/app /srv/logs
WORKDIR /usr/src/app

# Install dependencies
COPY requirements.txt /usr/src/app/
RUN pip install --no-cache-dir -r requirements.txt
RUN cron

# Copy application files
COPY . /usr/src/app/

# Port to expose
EXPOSE 8000

# Copy entrypoint script into the image
COPY docker_entrypoint.sh /docker_entrypoint.sh
RUN chmod +x /docker_entrypoint.sh
CMD ["/docker_entrypoint.sh"]

Upvotes: 1

Views: 2438

Answers (1)

Tirzono
Tirzono

Reputation: 436

If you want to run management commands periodically, have a look at Celery and use Celery beat. You can run tasks that call the management commands on specific times, the same as you would do with cron. Django has a way to call management commands from within the code. You can run Celery and Celery beat from your docker-compose setup.

from celery import shared_task
from django.core.management import call_command

@shared_task
def management_command_task():
    call_command('my_command', 'foo', bar='baz')

Upvotes: 1

Related Questions