In this lesson, you will learn how to use multi-stage Dockerfiles to create lightweight, immutable, and production-ready images for your Python CLI tools.
The Problem: Bloat and Security
When you package a Python application, your environment often contains unnecessary build tools, cache files, and development dependencies. If you simply copy your entire project directory into a Docker image, you risk leaking secrets, including irrelevant files, and creating a bloated "attack surface."
The Solution: Multi-Stage Builds
A multi-stage build allows you to use one "stage" to compile or install your dependencies and a second, final stage to package only the necessary runtime artifacts. This ensures your final image is minimal and consistent across any machine.
Consider this Dockerfile structure:
# Stage 1: Builder
FROM python:3.11-slim AS builder
WORKDIR /app
COPY pyproject.toml poetry.lock ./
RUN pip install poetry && poetry export -f requirements.txt > requirements.txt
RUN pip install --user -r requirements.txt
# Stage 2: Final Runtime
FROM python:3.11-slim
WORKDIR /app
# Copy only the installed dependencies from the builder
COPY --from=builder /root/.local /root/.local
COPY . .
# Ensure the local binaries are in the PATH
ENV PATH=/root/.local/bin:$PATH
ENTRYPOINT ["python", "main.py"]
Why this works
- Separation of Concerns: The first stage (
builder) handles the heavy lifting of installing dependencies. It can contain compilers (likegcc) that you don't want in your production container. - Immutability: By copying only the resulting environment (
/root/.local) and your source code into the final stage, you create a "distroless-like" image. - Efficiency: Docker caches these stages independently. If your source code changes but your dependencies don't, Docker skips the expensive installation stage, making your build pipeline significantly faster.
By adopting this pattern, you move beyond "it works on my machine" and ensure that your CLI tool executes within an isolated, reproducible environment that behaves exactly the same in CI/CD as it does on your local workstation.
Key Takeaway: Use multi-stage builds to discard build-time overhead, resulting in smaller, more secure, and highly portable images that guarantee consistent execution.