Run Your Python Script in Docker in 5 Minutes

Published on: May 31, 2026
Reading time: 4 minutes
Execução de scripts Python com Docker em containers

Container technology has revolutionized how we develop and distribute software. If you have ever been frustrated by code that works perfectly on your machine but throws errors when sent to a server or a colleague, learning how to run your Python script in Docker in 5 minutes is the definitive fix. Docker creates an isolated environment, guaranteeing that all dependencies, libraries, and OS configurations are exactly the same regardless of where the container runs. Mastering this tool is a key step in your Python roadmap, elevating your technical level from beginner to a professional ready for the DevOps and Cloud Computing market.

What is Docker and why use it with Python?

Think of Docker as a virtual box that contains everything your program needs to live: the interpreter, the installed Python libraries, and even system variables. That blueprint is called an image. When you run the image, it becomes a container.

For anyone working with Python for automation or data science, Docker solves package version conflicts. If one project needs Pandas 1.0 and another needs Pandas 2.0, containers keep those versions separate without interference. According to the Docker documentation, containerization enables unprecedented portability, saving hours of manual environment setup.

Prerequisites

You need Docker Desktop (available for Windows, Mac, and Linux) and a code editor like VS Code. You do not need Python installed directly on your physical machine — Docker handles that inside the container.

Step 1: Create the Python script

Create a folder called “my-docker-project” and inside it create main.py:

import os
import platform

def greet():
    print("Hello! This script is running inside a Docker container!")
    print(f"Operating System: {platform.system()}")
    print(f"Python Version: {platform.python_version()}")

    user = os.getenv("USERNAME", "Developer")
    print(f"Welcome, {user}!")

if __name__ == "__main__":
    greet()

Step 2: Create the requirements file

requests==2.31.0

Step 3: Write the Dockerfile

Create a file named Dockerfile (capital D, no extension):

# 1. Choose the official Python base image
FROM python:3.11-slim

# 2. Set the working directory inside the container
WORKDIR /app

# 3. Copy the requirements file first (for caching)
COPY requirements.txt .

# 4. Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# 5. Copy the rest of your project files
COPY . .

# 6. Define the command to run the script
CMD ["python", "main.py"]

Using -slim base images drastically reduces the final image size, making downloads and execution much faster. Keeping the pip install step before COPY . . leverages Docker’s layer caching — dependencies are only reinstalled when requirements.txt changes, not on every code edit.

Step 4: Build the Docker image

docker build -t my-python-script .

The -t flag gives the image a name (tag). The final dot tells Docker the Dockerfile is in the current folder.

Step 5: Run the container

# Basic run
docker run my-python-script

# With an environment variable
docker run -e USERNAME=Alice my-python-script

You will see the greeting message and the internal OS information. Passing environment variables via -e is the standard way to configure containers without hardcoding sensitive data — a best practice consistent with reading Python environment variables.

Image optimization tips

A common mistake is building gigantic images over 1 GB. Use a .dockerignore file to prevent copying unnecessary files such as __pycache__ folders or local virtual environments. For advanced use cases, multi-stage builds separate the compilation environment from the final runtime environment, producing even smaller images.

Why learn Docker today?

In today’s technology landscape, knowing how to write code is no longer enough. Docker is not just for simple scripts — it is the foundation for orchestrators like Kubernetes, used by the largest companies in the world to manage billions of requests per second. Sharing your project becomes trivial: instead of sending a .py file and hoping the recipient has everything installed, you share the Dockerfile and guarantee 100% successful execution on any machine.

Frequently Asked Questions

Do I need Python installed to use Docker?

No. Docker downloads the official Python image and runs the code inside it. You only need Docker installed on your machine.

What is the difference between an image and a container?

An image is the static blueprint (like an installer). A container is the running instance of that image (like the opened program).

Does Docker make Python slower?

Performance loss is minimal and imperceptible for most applications, because Docker is not a full virtual machine but a process isolation layer.

How do I save data generated by the script to my computer?

Use Docker Volumes to map a folder on your PC to a folder inside the container: docker run -v /local/path:/app/data my-python-script.

How do I see which containers are currently running?

Run docker ps in your terminal to list all active containers.

How do I delete old Docker images?

Run docker image prune to remove unused images and free up disk space.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Gerenciamento de dependências Python com Poetry
    IDEs and Tools
    Foto de perfil de Leandro Hirt da Academify

    Manage Python Dependencies with Poetry

    Learn how to manage Python dependencies with Poetry: install it, add/remove packages, understand poetry.lock, use dev groups, Docker integration, and

    Ler mais

    Tempo de leitura: 4 minutos
    31/05/2026
    Criação de ambiente Conda para projetos Python
    IDEs and Tools
    Foto de perfil de Leandro Hirt da Academify

    Create a Python Conda Environment in Minutes

    Learn how to create a Conda environment for Python in minutes: install Miniconda, activate environments, install packages, export to YAML,

    Ler mais

    Tempo de leitura: 4 minutos
    31/05/2026
    Automação de testes Python usando GitHub Actions
    IDEs and Tools
    Foto de perfil de Leandro Hirt da Academify

    Automate Python Tests with GitHub Actions in 5 Minutes

    Learn how to automate Python tests with GitHub Actions in 5 minutes using pytest, a YAML workflow, dependency installation, and

    Ler mais

    Tempo de leitura: 6 minutos
    29/05/2026
    Criação de pacote pip instalável em Python passo a passo
    IDEs and Tools
    Foto de perfil de Leandro Hirt da Academify

    Create an Installable Python Package

    Learn how to create an installable Python package with pyproject.toml, build, twine, TestPyPI, package structure, metadata, and publishing tips.

    Ler mais

    Tempo de leitura: 9 minutos
    28/05/2026
    Instalador do Python com a opção "Add Python.exe to PATH" marcada
    IDEs and Tools
    Foto de perfil de Leandro Hirt da Academify

    How to Install Python on Your PC Step-by-Step (2026)

    Python is one of the most popular programming languages in the world. It is beginner-friendly, powerful, and used in many

    Ler mais

    Tempo de leitura: 6 minutos
    08/05/2026
    Tela do VS Code mostrando o marketplace de extensões com destaque para a extensão Python da Microsoft
    IDEs and Tools
    Foto de perfil de Leandro Hirt da Academify

    10 Must-Have VS Code Extensions for Python Developers in 2026

    Visual Studio Code is still one of the best code editors for Python developers in 2026. It is lightweight, customizable,

    Ler mais

    Tempo de leitura: 7 minutos
    08/05/2026