Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

1.9 KB
Raw Blame
# ©AngelaMos | 2026
# fastapi.prod
#
# Multi-stage production Dockerfile for the FastAPI backend
#
# Builder stage: python:3.14-slim with uv, compiles
# requirements from pyproject.toml with ml extras and
# installs to /app/deps. Runtime stage: python:3.14-slim
# with libpq5 and curl, copies the dependency tree to a
# non-root appuser site-packages path, copies backend source
# and entrypoint, creates model directory, and runs uvicorn
# without --reload. Includes a HEALTHCHECK on /health.
# Connects to compose.yml, entrypoint.sh

FROM python:3.14-slim AS builder

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1

WORKDIR /app

COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    build-essential \
    libpq-dev && \
    rm -rf /var/lib/apt/lists/*

COPY backend/pyproject.toml ./
RUN uv pip compile pyproject.toml --extra ml -o requirements.txt && \
    uv pip install --target /app/deps -r requirements.txt

FROM python:3.14-slim

WORKDIR /app

RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    libpq5 \
    curl && \
    rm -rf /var/lib/apt/lists/* && \
    useradd -m -u 1000 appuser

COPY --from=builder /app/deps /home/appuser/.local/lib/python3.14/site-packages
ENV PYTHONPATH=/home/appuser/.local/lib/python3.14/site-packages:$PYTHONPATH \
    PATH=/home/appuser/.local/lib/python3.14/site-packages/bin:$PATH

COPY backend/ .
COPY infra/docker/entrypoint.sh /app/entrypoint.sh

RUN mkdir -p /app/data/models && \
    chmod +x /app/entrypoint.sh && \
    chown -R appuser:appuser /app
USER appuser

EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=10s --start-period=180s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

ENTRYPOINT ["/app/entrypoint.sh"]
CMD ["uvicorn", "app.factory:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000"]