Skip to content

Docker knowledge

How to Dockerize a Python Script

Create the script

  • Create a file called script.py
# script.py
# Writes a timestamp to /var/log/cron.log each time it runs.

import datetime

with open('/var/log/cron.log', 'a') as f:
    f.write(f'Running script at {datetime.datetime.now()}\n')

Create crontab file:

* * * * * root python3 /app/script.py >> /var/log/cron.log 2>&1
  • * * * * * specifies the cron schedule (every minute).
  • root is the user context under which the command will run.
  • python3 /app/script.py is the command to run your Python script.
  • >> /var/log/cron.log 2>&1 redirects stdout and stderr to /var/log/cron.log.

Create a virtual Python environment

python3 -m venv .venv

# Activate the Python environment
source .venv/bin/activate

Install packages

pip install (packages)

Save Pip installed packages

pip freeze > requirements.txt

Create a Dockerfile

  • Create a file called Dockerfile (no extension)
# Use an official Python runtime as a parent image
FROM python:3.12-slim

# Set the working directory in the container
WORKDIR /app

# Copy the script into the container
COPY script.py /app/script.py

# Install any needed packages specified in requirements.txt
# If your script requires any additional packages, include them here
# COPY requirements.txt /app/requirements.txt
# RUN pip install --no-cache-dir -r requirements.txt

# Copy the crontab file to the cron.d directory
COPY crontab /etc/cron.d/crontab

# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/crontab

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

# Run the command on container startup
CMD ["cron", "-f"]

Build Docker image

docker build -t my-python-script .

Test the Docker Image

Ensure your script works inside the container:

docker run --name my-python-cron-container -d my-python-cron

This starts the container in detached mode (-d).

If everything works as expected, proceed to setting up cron.

Verify Execution: Check the logs to verify that your script is running every minute.

docker logs my-python-cron-container

You should see output similar to:

Running script at 2024-06-21 12:00:00.123456
Running script at 2024-06-21 12:01:00.123456

Notes

  • Crontab File Permissions: Ensure that the permissions on your crontab file (0644 in the Dockerfile) allow cron to read it.
  • Logging: Ensure that your script logs to a location within the Docker container (/var/log/cron.log in this example) so that you can monitor its output.
  • Container Lifecycle: The cron job will run as long as the Docker container is running. If you stop the container (docker stop my-python-cron-container) and start it again, the cron job will resume.