Production Dockerfile for a Python service: multi-stage, non-root, healthcheck

Backend Live Coding November 13, 2026 dockerfile

Multi-stage for a smaller image, a non-root user, pinned versions, a .dockerignore (no .env or .git inside the image), PYTHONUNBUFFERED so logs show up immediately.

docker
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# ======================================================================
# Q: Write a production Dockerfile for a Python service.
#
# Multi-stage for a smaller image, a non-root user, pinned versions, a
# .dockerignore (no .env or .git inside the image), PYTHONUNBUFFERED so logs
# show up immediately. Secrets come from env/a secret manager at runtime, never
# at build time. The same image runs as the API, as a Celery worker and as beat,
# with a different command.
# ======================================================================

FROM python:3.12-slim AS build
ENV PIP_NO_CACHE_DIR=1
WORKDIR /app
COPY requirements.txt .
RUN pip wheel --wheel-dir /wheels -r requirements.txt

FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
RUN useradd --create-home --uid 10001 app
WORKDIR /app
COPY --from=build /wheels /wheels
RUN pip install --no-cache-dir /wheels/* && rm -rf /wheels
COPY --chown=app:app . .
USER app                                  # not root
EXPOSE 8000
HEALTHCHECK CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"
CMD ["gunicorn", "app.main:app", "-k", "uvicorn.workers.UvicornWorker",
     "-w", "4", "-b", "0.0.0.0:8000"]