How to Containerize Python Scripts Using Docker

Cloud & DevOps

16 March, 2026

how-to-containerize-python-scripts-using-docker
Ajaysingh Narayansingh Rajpurohit

Ajaysingh Narayansingh Rajpurohit

Sr Developer, Softices

Python scripts are commonly used for tasks such as automation, data processing, file handling, or building small APIs. A developer may write a script that runs perfectly on their own computer, but when another person tries to run it, errors often appear.

These problems usually occur because the environment on the other machine is different. The script may depend on specific packages, a particular version of Python, or certain system settings.

Common errors include:

  • missing libraries
  • incompatible Python versions
  • dependency conflicts

The code itself may be correct, but the system configuration is not the same.

Using Docker solves this problem. Docker allows you to package your Python script together with the environment it needs. Anyone with Docker installed can run the script without installing dependencies or configuring Python.

In this guide, you will learn how to package a script written in Python into a Docker container so it runs the same way on any machine.

Why Python Scripts Fail When Shared Across Different Machines

A Python script depends on more than just the code written in the .py file. It also relies on libraries, system tools, and environment settings. When these differ between machines, the script may stop working.

1. Missing Dependencies

Many Python projects use external libraries. If another user does not have those libraries installed, the script will fail.

Example error:

ModuleNotFoundError: No module named 'pandas'

This means the required package is not available in the environment.

2. Python Version Differences

Different versions of Python may behave differently. A script written for Python 3.11 may not run correctly on Python 3.8 because some features may be missing or deprecated.

3. Operating System Differences

A script that works on macOS might fail on Windows or Linux because of:

  • File path differences
  • System-level dependencies
  • OS-specific commands

For example:

/home/user/file.txt

is common on Linux or macOS, while Windows uses:

C:\Users\user\file.txt

4. Environment Configuration

Some scripts rely on environment variables or system libraries. If these are not configured properly, the script may fail even if the code is correct.

These issues make it difficult to share Python scripts between developers.

Docker solves this by packaging the script together with its environment.

What Docker Does that Helps Containerize Python Scripts Easily

Docker allows developers to create containers to run applications. A container includes:

  • the application code
  • the programming language runtime
  • libraries and dependencies
  • system tools required to run the application

Once packaged inside a container, the application runs the same way on any machine that has Docker installed.

Instead of sharing a script and asking others to install several dependencies, you can simply share a Docker image.

Prerequisites for Containerizing a Python Script with Docker

To follow this guide, you should have:

  • Python installed
  • Docker installed
  • Basic knowledge of the command line

You can download Docker from the official website and install it on your system. Then, you can begin creating your container.

Step 1: Create a Python Script That Will Run Inside Docker

Start with a simple script called app.py.

import requests

import sys

import os


def main():

  # Example of using environment variables

  api_url = os.getenv('API_URL', 'https://api.github.com')

   

  # Example of handling command-line arguments

  if len(sys.argv) > 1:

    api_url = sys.argv[1]

   

  try:

    response = requests.get(api_url)

    print(f"Status Code: {response.status_code}")

    print(f"Content Type: {response.headers.get('content-type', 'unknown')}")

  except Exception as e:

    print(f"Error: {e}")

    sys.exit(1)


if __name__ == "__main__":

  main()

This script:

  • Sends a request to an API
  • prints the status code
  • allows a custom URL through command-line argument
  • reads configuration from environment variables
  • Includes error handling

Since it uses the requests library, that dependency must also be installed.

Step 2: Define Python Dependencies Using requirements.txt

Python projects usually list dependencies in a file called requirements.txt.

Create a file named requirements.txt with the following content:

requests==2.31.0

This file tells Python which packages are required for the project and specifies exact versions for reproducibility.

Step 3: Create a .dockerignore File to Keep Docker Images Small

A .dockerignore file prevents unnecessary files from being copied into the container.

Create the file with the following content:

__pycache__

*.pyc

.env

.git

.gitignore

.vscode

.idea

This keeps the Docker image smaller and cleaner.

Step 4: Create a Dockerfile to Containerize the Python Script

A Dockerfile defines how the container should be built.

Create a file named Dockerfile in the same folder.

# Use an official Python runtime as the base image

FROM python:3.11-slim


# Set environment variables

ENV PYTHONUNBUFFERED=1 \

  PYTHONDONTWRITEBYTECODE=1 \

  PIP_NO_CACHE_DIR=1 \

  PIP_DISABLE_PIP_VERSION_CHECK=1


# Set the working directory in the container

WORKDIR /app


# Copy the requirements file first (for better caching)

COPY requirements.txt .


# Install dependencies

RUN pip install --no-cache-dir -r requirements.txt


# Copy the rest of the application code

COPY . .


# Specify the command to run when the container starts

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

Here is what each instruction does:

  • FROM python:3.11-slim: Uses a lightweight Python base image.
  • ENV: Configures Python to run properly inside containers.
  • WORKDIR /app: Creates and sets /app as the working directory.
  • COPY requirements.txt: Copies the dependency file first so Docker can reuse cached layers.
  • RUN pip install -r requirements.txt: Installs the required Python libraries without caching.
  • COPY . .: Copies all remaining project files into the container.
  • CMD ["python", "app.py"]: Runs the Python script when the container starts.

Step 5: Build a Docker Image for Your Python Script

Next, build the Docker image.

Run this command in your project folder:

docker build -t python-script .

This command creates a Docker image named python-script.

The build process reads the Dockerfile and installs everything needed for the script.

Step 6: Run the Docker Container to Execute the Python Script

Once the image is built, run the container:

docker run python-script

The container will execute the Python script and display the output.

Example output:

Status Code: 200

Content Type: application/json

This confirms the script runs successfully inside the container.

How to Share Dockerized Python Scripts with Other Developers 

After packaging the script with Docker, sharing it becomes much easier. There are a few common methods.

Method 1: Share the Project Repository

Upload the project to a Git repository containing:

  • Python script
  • Dockerfile
  • requirements.txt
  • .dockerignore
  • README with instructions

Anyone can clone the repository and run:

git clone repository_url

cd project

docker build -t python-script .

docker run python-script

Method 2: Share the Docker Image

You can also upload the image to a container registry like Docker Hub.

Steps:

1. Tag the image with your Docker Hub username:

docker tag python-script username/python-script:latest

2. Push the image

docker push username/python-script:latest

3. Others can download and run it with:

docker run username/python-script:latest

Method 3: Save and Load the Image (Air-gapped Environments)

For systems without internet access:

# Save the image to a tar file

docker save -o python-script.tar python-script

# Compress for easier transfer

gzip python-script.tar

# On the target machine, load the image

docker load -i python-script.tar.gz

Benefits of Using Docker to Share and Run Python Scripts

Using Docker provides several practical advantages.

  • Consistent Execution: The script runs the same way everywhere because the environment is identical.
  • Easy Collaboration: Team members do not need to install multiple libraries or configure Python versions.
  • Faster Setup: New developers can run the project immediately without spending time on setup.
  • Simple Distribution: The entire application can be shared as a single container image.
  • Version Control: You can tag different versions of your script and its environment.
  • Isolation: Different projects with conflicting dependencies can run side by side.

When You Should Use Docker for Python Projects

Docker is especially helpful for certain types of Python projects:

  • Automation Scripts: Scripts used for scheduled jobs or system automation run reliably everywhere.
  • Data Processing Tasks: Data pipelines and scripts that rely on multiple libraries(pandas, numpy, etc.).
  • APIs: Python APIs built with frameworks like Flask or FastAPI can be deployed consistently.
  • Machine Learning Applications: Projects that require many dependencies and specific versions of TensorFlow, PyTorch, etc.
  • Legacy Applications: Keep old Python 2 scripts running with their original dependencies
  • CI/CD Pipelines: Run tests in the same environment as production.

Essential Commands for Managing Docker Containers

Here's a quick reference of useful Docker commands:

Command

Purpose

docker build -t name . Build an image from a Dockerfile
docker run name Run a container from an image
docker ps List running containers
docker ps -a List all containers (including stopped)
docker stop container_id Stop a running container
docker rm container_id Remove a container
docker rmi image_name Remove an image
docker images List all images
docker logs container_id View container logs
docker exec -it container_id bash Access a running container's shell


Troubleshooting Python Scripts Running in Docker

Issue 1: Build Fails with "Could not find a version that satisfies the requirement"

Solution: Check your internet connection and ensure the package name is correct. Use specific versions to avoid compatibility issues.

Issue 2: Container Runs but Script Fails

Solution: Check the logs with docker logs container_id. Add debugging output to your script.

Issue 3: Permission Denied When Mounting Volumes

Solution: On Linux, you may need to adjust permissions or use :Z for SELinux:

docker run -v $(pwd)/data:/app/data:Z python-script

Issue 4: Image Too Large

Solution: Use slim Python images (python:3.11-slim) and clean up cache in Dockerfile:

RUN pip install --no-cache-dir -r requirements.txt && \

  rm -rf /root/.cache/pip

Best Practices to Dockerize Python Scripts

  • Pin dependency versions in requirements.txt for reproducibility
  • Use .dockerignore to keep images small
  • Leverage Docker cache by copying requirements file first
  • Use slim base images to reduce image size
  • Set environment variables for configuration
  • Use volumes for persistent data and input/output
  • Add health checks for long-running scripts
  • Tag images properly with version numbers

A Reliable Way to Run Python Scripts Across Any Environment  

Sharing Python scripts can be difficult when different systems use different environments. Missing packages, incompatible versions, and configuration issues often cause scripts to fail.

Using Docker to make a Python script shareable solves this problem by packaging the code and its environment together. Anyone with Docker installed can run the script without additional setup.

By creating a Dockerfile, building an image, and running a container, you can make your Python scripts portable and easy to share across teams and machines.

For developers who frequently collaborate or distribute scripts, this approach saves time and prevents many common environment-related issues. Whether you're sharing a simple automation script or a complex data processing pipeline, Docker ensures it runs exactly as intended, everywhere.


migrate-uikit-to-swiftui-ios-app

Previous

Migrating an Existing iOS App UI from Swift (UIKit) to SwiftUI

Next

How to Analyze an IPO Before Investing

how-to-analyze-ipo-before-investing

Frequently Asked Questions (FAQs)

To dockerize a script written in Python, you need to create a Dockerfile, define dependencies in a requirements.txt file, build an image using Docker, and run the script inside a container. This packages the code and its environment together.

Yes. Containers created with Docker run consistently across different operating systems such as Windows, macOS, and Linux, as long as Docker is installed on the system.

One of the easiest ways is to containerize the script using Docker. By sharing a Docker image or repository, other users can run the script without manually installing dependencies.

No. A Docker container can include the required version of Python along with all necessary libraries, so the host system does not need Python installed.

Running scripts in Docker containers provides consistent environments, easier collaboration, faster setup for new developers, and simplified distribution of applications.

Yes. Docker is widely used to deploy Python applications, including APIs built with frameworks like Flask or FastAPI, as well as automation scripts, data pipelines, and machine learning services.

Yes. Docker is commonly used to package and deploy larger applications such as APIs built with frameworks like Flask or FastAPI, as well as data processing and machine learning projects.