|
1 | | -FROM python:3.10-slim |
| 1 | +# Stage 1: Builder |
| 2 | +FROM python:3.10-alpine as builder |
| 3 | + |
| 4 | +# Set environment variables |
| 5 | +ENV PYTHONDONTWRITEBYTECODE=1 \ |
| 6 | + PYTHONUNBUFFERED=1 |
2 | 7 |
|
3 | 8 | WORKDIR /code |
4 | 9 |
|
5 | | -COPY ./requirements.txt /code/requirements.txt |
| 10 | +# Install system dependencies required for building python packages |
| 11 | +# libffi-dev and build-base are often needed for python wheels on alpine |
| 12 | +RUN apk add --no-cache libffi-dev build-base |
| 13 | + |
| 14 | +# Install poetry and export plugin |
| 15 | +RUN pip install poetry poetry-plugin-export |
| 16 | + |
| 17 | +# Copy poetry configuration |
| 18 | +COPY pyproject.toml poetry.lock . |
| 19 | + |
| 20 | +# Generate lock file and export requirements.txt |
| 21 | +RUN poetry lock && \ |
| 22 | + poetry export -f requirements.txt --output requirements.txt --without-hashes |
| 23 | + |
| 24 | +# Install python dependencies |
| 25 | +RUN pip wheel --no-cache-dir --no-deps --wheel-dir /code/wheels -r requirements.txt |
6 | 26 |
|
7 | | -RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt |
| 27 | +# Stage 2: Runner |
| 28 | +FROM python:3.10-alpine as runner |
| 29 | + |
| 30 | +# Metadata |
| 31 | +LABEL maintainer="Monolith Team" \ |
| 32 | + description="Monolithic FastAPI Service" \ |
| 33 | + version="1.0" |
| 34 | + |
| 35 | +ENV PYTHONDONTWRITEBYTECODE=1 \ |
| 36 | + PYTHONUNBUFFERED=1 |
| 37 | + |
| 38 | +WORKDIR /code |
8 | 39 |
|
| 40 | +# Create a non-root user for security |
| 41 | +# Alpine uses adduser -D (no password) |
| 42 | +RUN addgroup -S appuser && adduser -S appuser -G appuser |
| 43 | + |
| 44 | +# Install system dependencies (curl for healthcheck) |
| 45 | +RUN apk add --no-cache curl |
| 46 | + |
| 47 | +# Copy wheels from builder stage |
| 48 | +COPY --from=builder /code/wheels /code/wheels |
| 49 | +COPY --from=builder /code/requirements.txt . |
| 50 | + |
| 51 | +# Install dependencies from wheels |
| 52 | +RUN pip install --no-cache-dir --no-index --find-links=/code/wheels -r requirements.txt && \ |
| 53 | + rm -rf /code/wheels |
| 54 | + |
| 55 | +# Copy application code |
9 | 56 | COPY ./app /code/app |
10 | 57 |
|
| 58 | +# Change ownership to non-root user |
| 59 | +RUN chown -R appuser:appuser /code |
| 60 | + |
| 61 | +# Switch to non-root user |
| 62 | +USER appuser |
| 63 | + |
| 64 | +# Expose the port |
| 65 | +EXPOSE 8000 |
| 66 | + |
| 67 | +# Healthcheck to ensure the service is running |
| 68 | +HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \ |
| 69 | + CMD curl -f http://localhost:8000/ || exit 1 |
| 70 | + |
| 71 | +# Command to run the application |
11 | 72 | CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] |
0 commit comments