Interview Prep/Build Tools (Java, Node.js, Python, .NET)/Python builds (pip, venv, requirements.txt)

How do you write a good Dockerfile for a Python application?

IntermediateConceptPython builds (pip, venv, requirements.txt)
Answer

Short answer

Use a python:3.12-slim base, set PYTHONDONTWRITEBYTECODE=1 and PYTHONUNBUFFERED=1, copy requirements first and install with --no-cache-dir so the dependency layer is cached, copy the code, run as a non-root user and start a production server (gunicorn/uvicorn) in exec form.

Example

FROM python:3.12-slim AS base
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1
WORKDIR /app

FROM base AS build
RUN apt-get update && apt-get install -y --no-install-recommends build-essential libpq-dev
COPY requirements.txt .
RUN python -m venv /venv && /venv/bin/pip install -r requirements.txt

FROM base
RUN apt-get update && apt-get install -y --no-install-recommends libpq5 && rm -rf /var/lib/apt/lists/*
COPY --from=build /venv /venv
COPY . .
RUN useradd -m app
USER app
ENV PATH="/venv/bin:$PATH"
EXPOSE 8000
CMD ["gunicorn", "-w", "3", "-b", "0.0.0.0:8000", "app:app"]

Why each part

Part Reason
slim base Much smaller than the full image; fewer CVEs
PYTHONUNBUFFERED=1 Logs show up immediately in kubectl logs
Build stage with compilers gcc and headers stay out of the final image
venv copied across stages One folder holds all installed packages
Non-root user Security best practice

What to say in the interview

"Slim base, unbuffered output, requirements copied before code for caching, compilers only in a build stage, a venv copied into the runtime stage, non-root user and gunicorn as the entrypoint."

All Build Tools (Java, Node.js, Python, .NET) questions Roadmap: Python apps: pip, venv & requirements.txt

More on Python builds (pip, venv, requirements.txt)