Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django + docker + periodic commands

What's the best practices for running periodic/scheduled tasks ( like manage.py custom_command ) when running Django with docker (docker-compose) ?

f.e. the most common case - ./manage.py clearsessions

  • Django recommends to run it with cronjobs...
  • But Docker does not recommend adding more then one running service to single container...

I guess I can create a docker-compose service from the same image for each command that i need to run - and the command should run infinite loop with a needed sleeps, but that seems overkill doing that for every command that need to be scheduled

What's your advice ?

like image 591
Pydev UA Avatar asked Dec 10 '22 09:12

Pydev UA


1 Answers

The way that worked for me

in my django project I have a crontab file like this:

0 0 * * * root python manage.py clearsessions     > /proc/1/fd/1 2>/proc/1/fd/2

Installed/configured cron inside my Dockerfile

RUN apt-get update && apt-get -y install cron
ADD crontab /etc/cron.d/crontab
RUN chmod 0644 /etc/cron.d/crontab

and in docker-compose.yml add a new service that will build same image as django project but will run cron -f as CMD

version: '3'
services:
  web:
    build: ./myprojectname
    ports:
     - "8000:8000"
    #...


  cronjobs:
    build: ./myprojectname
    command: ["cron", "-f"]
like image 152
Pydev UA Avatar answered Jan 03 '23 01:01

Pydev UA