Skip to content

Containerizing Python Scripts for Beginners

This is a tutorial explaining how to containerize a python script.

Containerization is a powerful tool for developers, especially when working with Python scripts. It helps package code and dependencies in a lightweight container image that can run consistently on any system. This guide walks you through containerizing a simple Python script using Docker.


Sample Python Script

Here's a basic Python script that performs a time-delayed computation using sleep and logs the process. It also uses pandas to simulate a dependency.

from time import sleep
from random import randint
import pandas as pd

def compute(seconds: int):
    print(f"Compute Time : {seconds}")
    print("Starting Computation.")
    sleep(seconds)
    print("Completed Computation.")

    return

if __name__ == "__main__":
    compute_time = randint(1, 9)
    compute(compute_time)

Dockerfile

FROM python:3.10

ENV PYTHONUNBUFFERED=1  

WORKDIR /myapp

COPY requirements.txt .

RUN pip install -r requirements.txt

COPY app.py .

CMD ["python3", "app.py"]

🔍 What’s Happening Here?

  • FROM python:3.10: Starts with an official Python base image.

  • ENV PYTHONUNBUFFERED=1: Ensures that all output is immediately printed to the logs (useful for debugging in containers).

  • WORKDIR /myapp: Sets the working directory inside the container.

  • COPY requirements.txt .: Copies the dependency list.

  • RUN pip install -r requirements.txt: Installs Python dependencies.

  • COPY app.py .: Adds your script into the container.

  • CMD ["python3", "app.py"]: Sets the default command to run the script.

Build the Docker image:

docker build -t python-compute-app .

Run the Docker container:

docker run --rm python-compute-app