✦ For everyone, free.

Practical knowledge for real and everyday life

Home

12.2.3.1 Python Requirements Install

A focused guide to Python Requirements Install, connecting core concepts with practical Docker and container operations.

Python requirements install reads a project's dependency declarations — typically a requirements.txt file, though modern tooling like Poetry or pip-tools offers alternatives — and installs them within a Docker build, structured for effective layer caching.

The Standard requirements.txt Pattern

Dependencies are copied and installed before the rest of the application's source code.

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

This ordering allows Docker to cache the install step separately, avoiding unnecessary reinstalls when only application code (not dependencies) changes.

Pinning Exact Dependency Versions for Reproducibility

A requirements.txt with exact, pinned versions (rather than loose version ranges) produces a more reproducible build, ensuring the exact same dependency versions are installed regardless of when the build actually runs.

flask==3.0.2
requests==2.31.0
flask>=3.0
requests

The first, pinned form guarantees consistent installs across builds; the second, unpinned form could resolve to different actual versions depending on what's available at build time.

Using Poetry or Pip-Tools for More Sophisticated Dependency Management

Projects using more sophisticated dependency management tooling adapt this same general pattern to their specific tool's conventions.

COPY pyproject.toml poetry.lock ./
RUN poetry install --no-root --only main
COPY . .
Installing Into a Specific Location for Multi-Stage Builds

For a multi-stage build separating dependency installation from the final runtime image, installing into a specific target directory simplifies copying just the installed packages forward.

RUN pip install --no-cache-dir --target=/install -r requirements.txt
COPY --from=build /install /usr/local/lib/python3.12/site-packages
Why Python Requirements Install Matters

Correctly structuring the dependency installation step — proper layer ordering, version pinning for reproducibility, appropriate handling for whichever specific tooling a project uses — is foundational to producing efficient, reliable Python container builds.