Convert to two-stage build: builder stage installs gcc and compiles Python C extensions, runtime stage copies only the installed packages. Removes gcc and postgresql-client from the production image, reducing attack surface. postgresql-client was unused (healthchecks use urllib). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
35 lines
1.2 KiB
Docker
35 lines
1.2 KiB
Docker
# ── Build stage: compile C extensions ──────────────────────────────────
|
|
FROM python:3.12-slim AS builder
|
|
|
|
WORKDIR /build
|
|
|
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
gcc \
|
|
&& rm -rf /var/lib/apt/lists/*
|
|
|
|
COPY requirements.txt .
|
|
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
|
|
|
|
# ── Runtime stage: lean production image ───────────────────────────────
|
|
FROM python:3.12-slim
|
|
|
|
WORKDIR /app
|
|
|
|
# Copy pre-built Python packages from builder
|
|
COPY --from=builder /install /usr/local
|
|
|
|
# Copy application code
|
|
COPY . .
|
|
|
|
# Create non-root user
|
|
RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app
|
|
USER appuser
|
|
|
|
EXPOSE 8000
|
|
|
|
# Run migrations and start server
|
|
# --no-server-header: suppresses uvicorn version disclosure
|
|
# --proxy-headers: reads X-Forwarded-Proto/For from reverse proxy so redirects use correct scheme
|
|
# --forwarded-allow-ips '*': trusts proxy headers from any IP (nginx is on Docker bridge network)
|
|
CMD ["sh", "-c", "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000 --no-server-header --proxy-headers --forwarded-allow-ips '*'"]
|