Use multi-stage builds. Typically, the first stage installs all dependencies into a dedicated folder, while the final production stage copies only the dependency folder and application code.
Use hardened container images from dhi.io for improved security and reduced attack surface.
Use environment variables such as:
ENV PYTHONUNBUFFERED=1
- PYTHONDONTWRITEBYTECODE → Prevents creation of
.pycfiles. - PYTHONUNBUFFERED → Enables immediate log flushing for containers.
In the production stage, always switch to a non-root / less privileged user.
Never hardcode or bake API keys into Dockerfiles or image layers using
ENV or ARG.
Pass secrets securely at runtime using environment variables provided by your orchestrator.
Use environment: blocks mapped to local .env files.
Ensure .env is listed in .gitignore.
| Setting | Purpose |
|---|---|
| --workers 4 | Restricts process spawning to a fixed, predictable resource footprint. |
| --proxy-headers | Safely handles trusted proxy headers when behind Nginx, Cloudflare, AWS ALB, etc. |
| --reload | Do NOT use in production. Prevents code injection and unsafe hot-reload behavior. |
# ==============================================================================
# STAGE 1: Builder
# ==============================================================================
# FROM dhi.io/python:3.13-dev AS builder
FROM python:3.13-slim AS builder
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
WORKDIR /build
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
gcc \
python3-dev \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir --target=/build/deps -r requirements.txt
# ==============================================================================
# STAGE 2: Secure Runtime
# ==============================================================================
FROM dhi.io/python:3.13-minimal AS runtime
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PYTHONPATH=/app/deps
WORKDIR /app
RUN groupadd -g 10001 appgroup && \
useradd -u 10001 -g appgroup -m -s /sbin/nologin appuser
COPY --from=builder --chown=appuser:appgroup /build/deps /app/deps
COPY --chown=appuser:appgroup . /app/
USER appuser
EXPOSE 8080
ENTRYPOINT ["python", "-m", "uvicorn", "main:app",
"--host", "0.0.0.0",
"--port", "8080",
"--workers", "4",
"--proxy-headers"]
No comments:
Post a Comment