How to run Python script or other job in Docker container with CRON
Shakhzhakhan Maxudbek

Shakhzhakhan Maxudbek @xinitd

About: System administrator, software engineer, technical blogger and open source contributor. Passionate about automation and cloud technologies.

Location:
Kazakhstan
Joined:
Nov 30, 2024

How to run Python script or other job in Docker container with CRON

Publish Date: Dec 30 '24
0 0

After we're figured out the setup cron jobs in operating system, it's time to learn how to run any scripts in Docker container.

Create folder with your project's name and create there four text files with following names:

myproject/
  - my_script.py
  - cronjob
  - Dockerfile
  - docker-compose.yaml
Enter fullscreen mode Exit fullscreen mode

File my_script.py need for run periodically. It may contain any code for your job. For example:

import requests
r = requests.get(url='https://example.com/')
if r.status_code == 200:
    # do something
else:
    # do something else
Enter fullscreen mode Exit fullscreen mode

File named as cronjob should contain Cron expression:

#####
*/5 * * * * /app/env/bin/python3 /app/my_script.py arg1 arg2 >> /app/logs/my_script.log 2>&1
#####
Enter fullscreen mode Exit fullscreen mode

Attention! Last line in cronjob file shouldn't be empty!

Now prepare Dockerfile:

FROM debian:stable
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
USER root
ARG APP=/app
WORKDIR ${APP}
RUN apt update
RUN apt install nano cron python3 python3-pip python3-venv -y
COPY . .
COPY cronjob /etc/cron.d/cronjob
RUN chmod 0644 /etc/cron.d/cronjob
RUN crontab /etc/cron.d/cronjob
RUN touch /var/log/cron.log
RUN python3 -m venv ${APP}/env/
RUN ${APP}/env/bin/pip install --no-cache-dir -r ${APP}/requirements.txt
CMD cron && tail -f /var/log/cron.log
Enter fullscreen mode Exit fullscreen mode

In the end we need configure restart policy in docker-compose.yaml file:

services:
  myproject:
    restart: unless-stopped
    build:
      context: .
Enter fullscreen mode Exit fullscreen mode

Now we ready for run:

docker compose up -d
Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment