How to run custom django-admin commands as a cron job in docker?
I have a django-app sample
. In this app I have created a file test.py
and wrote my custom commands in it as mentioned in the django official documentation
sample/
__init__.py
models.py
management/
__init__.py
commands/
__init__.py
test.py
views.py
test.py:
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
# Sample content
print("Hello World")
I had run the command python manage.py test
and it is working. What I need is that I want to run this command as a cron job in docker. I had tried this, created a cron file hello-cron
.
hello-cron:
* * * * * root python /home/manage.py test >> /home/cron.log 2>&1
# Empty line
Dockerfile:
FROM python:3.10.6
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
WORKDIR /home
COPY requirements.txt /home/
RUN pip install -r requirements.txt
COPY . /home/
RUN apt-get update && apt-get -y install cron
COPY hello-cron /home/hello-cron
RUN chmod 0644 /home/hello-cron
RUN chmod 0744 /home/sample/management/commands/test.py
RUN crontab /home/hello-cron
RUN touch /home/cron.log
CMD cron && tail -f /home/cron.log
docker-compose.yml:
version: "3.9"
services:
db:
image: postgres
volumes:
- ./data/db:/var/lib/postgresql/data
environment:
- POSTGRES_DB=postgres
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
web:
restart: always
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/home
ports:
- "8000:8000"
environment:
- POSTGRES_NAME=postgres
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
depends_on:
- db
I had run the container by using the command docker-compose up --build
, but cron job is not working.