How to Run a Python Script as a Cron Job | Docker + Cron

Ganesh Prasad
4 min readFeb 3, 2024

In this article, we will see one of many ways to schedule a corn job (a Python script) using docker and cron.

Contents

Python script
Folder contents
Cron job Specification
Script Logs
Dockerfile definition
Docker image build/push/run

  • Cron: a tool that comes already installed on most Linux distributions or can be installed apt-get install cron.
  • Docker: a tool to develop, ship, or run applications in containers (portable, lightweight, and isolated).

A Simple Python Script

For our purpose, let’s create a simple Python script, your’s can be complicated as hell, though!

from datetime import datetime

print("*" * 50)
print("Hi from Cron 1")
print("current time: ", datetime.time())
print("*" * 50)

Folder Structure

Let’s now discuss the directory and the contents it will have.

Required files for cron using a docker.

requirements.txt
A file with all the Python packages that your script will need. In our case, it will be empty, but let’s say you need pandas and Numpy.

--

--

Ganesh Prasad

Backend Developer at Appscrip | C++ veteran, 💜 Dart