|
| 1 | +# syntax=docker/dockerfile:1 |
| 2 | + |
| 3 | +# ===== Build Stage ===== |
| 4 | +FROM python:3.12-slim AS builder |
| 5 | + |
| 6 | +# Set environment variables |
| 7 | +ENV PYTHONDONTWRITEBYTECODE=1 \ |
| 8 | + PYTHONUNBUFFERED=1 \ |
| 9 | + PIP_NO_CACHE_DIR=1 \ |
| 10 | + PIP_DISABLE_PIP_VERSION_CHECK=1 |
| 11 | + |
| 12 | +WORKDIR /app |
| 13 | + |
| 14 | +# Install build dependencies |
| 15 | +RUN apt-get update && apt-get install -y --no-install-recommends \ |
| 16 | + build-essential \ |
| 17 | + libpq-dev \ |
| 18 | + && rm -rf /var/lib/apt/lists/* |
| 19 | + |
| 20 | +# Install PDM |
| 21 | +RUN pip install pdm |
| 22 | + |
| 23 | +# Copy dependency files |
| 24 | +COPY pyproject.toml pdm.lock* ./ |
| 25 | + |
| 26 | +# Export dependencies to requirements.txt and install |
| 27 | +# If pdm.lock exists, use it; otherwise install from pyproject.toml |
| 28 | +RUN pdm lock --prod 2>/dev/null || true && \ |
| 29 | + pdm export --prod -o requirements.txt --without-hashes && \ |
| 30 | + pip install --prefix=/install -r requirements.txt |
| 31 | + |
| 32 | + |
| 33 | +# ===== Production Stage ===== |
| 34 | +FROM python:3.12-slim AS production |
| 35 | + |
| 36 | +# Set environment variables |
| 37 | +ENV PYTHONDONTWRITEBYTECODE=1 \ |
| 38 | + PYTHONUNBUFFERED=1 \ |
| 39 | + PYTHONPATH=/app \ |
| 40 | + ENV=production |
| 41 | + |
| 42 | +WORKDIR /app |
| 43 | + |
| 44 | +# Install runtime dependencies |
| 45 | +RUN apt-get update && apt-get install -y --no-install-recommends \ |
| 46 | + libpq5 \ |
| 47 | + && rm -rf /var/lib/apt/lists/* \ |
| 48 | + && groupadd -r appgroup && useradd -r -g appgroup appuser |
| 49 | + |
| 50 | +# Copy installed packages from builder |
| 51 | +COPY --from=builder /install /usr/local |
| 52 | + |
| 53 | +# Copy application code |
| 54 | +COPY . . |
| 55 | + |
| 56 | +# Create logs directory for gunicorn |
| 57 | +RUN mkdir -p logs && chown -R appuser:appgroup /app |
| 58 | + |
| 59 | +# Switch to non-root user |
| 60 | +USER appuser |
| 61 | + |
| 62 | +# Expose port |
| 63 | +EXPOSE 8000 |
| 64 | + |
| 65 | +# Health check |
| 66 | +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ |
| 67 | + CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/heartbeat')" || exit 1 |
| 68 | + |
| 69 | +# Run the application with uvicorn |
| 70 | +CMD ["python", "-m", "uvicorn", "run:app", "--host", "0.0.0.0", "--port", "8000"] |
0 commit comments