|
| 1 | +# Multi-stage build for optimized image size |
| 2 | +FROM python:3.11-slim AS builder |
| 3 | + |
| 4 | +# Set working directory |
| 5 | +WORKDIR /app |
| 6 | + |
| 7 | +# Install system dependencies required for building |
| 8 | +RUN apt-get update && apt-get install -y --no-install-recommends \ |
| 9 | + gcc \ |
| 10 | + libpq-dev \ |
| 11 | + && rm -rf /var/lib/apt/lists/* |
| 12 | + |
| 13 | +# Copy requirements and install Python dependencies |
| 14 | +COPY requirements.txt . |
| 15 | +RUN pip install --no-cache-dir --user -r requirements.txt |
| 16 | + |
| 17 | +# Final stage |
| 18 | +FROM python:3.11-slim |
| 19 | + |
| 20 | +# Set environment variables |
| 21 | +ENV PYTHONUNBUFFERED=1 \ |
| 22 | + PYTHONDONTWRITEBYTECODE=1 \ |
| 23 | + PIP_NO_CACHE_DIR=1 \ |
| 24 | + PYTHONPATH=/app |
| 25 | + |
| 26 | +# Set working directory |
| 27 | +WORKDIR /app |
| 28 | + |
| 29 | +# Install runtime system dependencies only |
| 30 | +RUN apt-get update && apt-get install -y --no-install-recommends \ |
| 31 | + libpq5 \ |
| 32 | + && rm -rf /var/lib/apt/lists/* |
| 33 | + |
| 34 | +# Create non-root user for security |
| 35 | +RUN useradd -m -u 1000 appuser |
| 36 | + |
| 37 | +# Copy Python dependencies from builder |
| 38 | +COPY --from=builder --chown=appuser:appuser /root/.local /home/appuser/.local |
| 39 | + |
| 40 | +# Copy application code |
| 41 | +COPY --chown=appuser:appuser . . |
| 42 | + |
| 43 | +# Add local pip installation to PATH |
| 44 | +ENV PATH=/home/appuser/.local/bin:$PATH |
| 45 | + |
| 46 | +# Switch to non-root user |
| 47 | +USER appuser |
| 48 | + |
| 49 | +# Expose port (adjust if needed) |
| 50 | +EXPOSE 8000 |
| 51 | + |
| 52 | +# Health check |
| 53 | +HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \ |
| 54 | + CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/').read()" || exit 1 |
| 55 | + |
| 56 | +# Run the application |
| 57 | +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] |
0 commit comments