| # ============================================= | |
| # Stage 1: Builder | |
| # ============================================= | |
| FROM python:3.11-slim AS builder | |
| WORKDIR /app | |
| # Install build dependencies | |
| RUN apt-get update && apt-get install -y --no-install-recommends \ | |
| gcc \ | |
| && rm -rf /var/lib/apt/lists/* | |
| # Copy and install Python deps | |
| COPY requirements.txt . | |
| RUN pip install --no-cache-dir --user -r requirements.txt | |
| # ============================================= | |
| # Stage 2: Final Runtime | |
| # ============================================= | |
| FROM python:3.11-slim | |
| WORKDIR /app | |
| # Copy installed packages from builder | |
| COPY --from=builder /root/.local /root/.local | |
| ENV PATH=/root/.local/bin:$PATH | |
| # Copy app | |
| COPY main.py . | |
| # Enable unbuffered output | |
| ENV PYTHONUNBUFFERED=1 | |
| # Expose FastAPI port | |
| EXPOSE 8000 | |
| # ============================================= | |
| # Auto-detect CPU cores and set Uvicorn workers | |
| # ============================================= | |
| CMD ["sh", "-c", "uvicorn main:app --host 0.0.0.0 --port 8000 --workers $(( $(nproc) * 2 ))"] |