Your First Python Dockerfile Blueprint
A Dockerfile is a recipe for building a self-contained environment for your Python app. Use it to ensure your app runs identically everywhere, from your laptop to production. The common footgun is forgetting a .dockerignore file, which bloats your image.
WHY IT EXISTS: To solve the "it works on my machine" problem. Python applications depend on specific interpreter versions, system libraries, and package versions. Managing these across different environments is complex and error-prone. A Dockerfile codifies the entire environment setup, making it repeatable and portable.
THE MENTAL MODEL: A Dockerfile is a blueprint for an assembly line. Each instruction (FROM, COPY, RUN, CMD) is a station. The raw materials are your source code and a base OS image. The finished product is a Docker image: a self-contained, runnable package of your application and its entire environment.
HOW IT WORKS: Docker reads the Dockerfile top-to-bottom, creating a new "layer" for each instruction. It starts with a base image using FROM (e.g., python:3.11-slim). WORKDIR sets the current directory inside the container. COPY adds files from your machine. RUN executes commands, like installing dependencies with pip. Finally, CMD specifies the default command to execute when a container starts. Docker aggressively caches these layers. If your code changes but your requirements.txt does not, Docker reuses the dependency layer, making rebuilds much faster.
WHEN TO USE IT: Use a Dockerfile for nearly any Python application you plan to deploy, share, or run in isolation. It's standard for web services (FastAPI, Django), data processing jobs, and machine learning models. It guarantees consistency from local development to cloud deployment on services like Kubernetes or AWS ECS.
WHEN NOT TO USE IT: For simple, single-file scripts with no external dependencies that are only run locally, a Dockerfile might be overkill. It's also less common for libraries intended to be installed via pip into other projects, as the consuming project typically manages its own environment.
ONE CANONICAL EXAMPLE: A common pattern for a FastAPI app is to optimize for caching. First, copy only the requirements file: COPY requirements.txt .. Then, install dependencies: RUN pip install --no-cache-dir -r requirements.txt. After that, copy the rest of your application source code: COPY . .. This ensures that changing your Python code doesn't force a time-consuming re-installation of all your packages on every build. The final line, CMD, would start the web server, like: CMD ["uvicorn", "main:app", "--host", "0.0.0.0"].
Read the original → docs.docker.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.