Docker and Python Virtual Environments


Docker tip:

You can use a virtual environment instead of building wheels in multi-stage builds.

For example:

# temp stage
FROM python:3.9-slim as builder

WORKDIR /app

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

RUN apt-get update && \
    apt-get install -y --no-install-recommends gcc

RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

COPY requirements.txt .
RUN pip install -r requirements.txt


# final stage
FROM python:3.9-slim

COPY --from=builder /opt/venv /opt/venv

WORKDIR /app

ENV PATH="/opt/venv/bin:$PATH"

Note: This is one of the only use cases for using a Python virtual environment with Docker.

  1. Install the dependencies in the builder image within a virtual environment.
  2. Copy over the dependencies to the final image

This reduces the size of the final image significantly.