feat: multi-stage build for slim image

This commit is contained in:
2025-10-07 07:58:08 +02:00
parent bc55b95bda
commit eb6da3d9cf
+19 -21
View File
@@ -1,28 +1,27 @@
# Use Python 3.13 slim image as base # Use Python 3.13 slim image as base
FROM python:3.13-slim FROM python:3.13-slim AS builder
# Set working directory # Set working directory
WORKDIR /app WORKDIR /app
# Set environment variables # # Install system dependencies
ENV PYTHONDONTWRITEBYTECODE=1 \ # RUN apt-get update && apt-get install -y \
PYTHONUNBUFFERED=1 \ # build-essential \
POETRY_NO_INTERACTION=1 \ # curl \
POETRY_VENV_IN_PROJECT=1 \ # && rm -rf /var/lib/apt/lists/*
POETRY_CACHE_DIR=/tmp/poetry_cache
# Install system dependencies
RUN apt-get update && apt-get install -y \
build-essential \
curl \
&& rm -rf /var/lib/apt/lists/*
# Copy requirements file # Copy requirements file
COPY requirements.txt . COPY requirements.txt .
# Install Python dependencies # Install Python dependencies
RUN pip install --no-cache-dir --upgrade pip && \ RUN pip install --no-cache-dir --no-deps \
pip install --no-cache-dir -r requirements.txt --disable-pip-version-check \
--target=/app/site-packages \
-r requirements.txt
FROM python:3.13-slim
COPY --from=builder /app/site-packages /app/site-packages
# Create a non-root user # Create a non-root user
RUN adduser --disabled-password --gecos '' appuser RUN adduser --disabled-password --gecos '' appuser
@@ -31,8 +30,11 @@ RUN adduser --disabled-password --gecos '' appuser
COPY ./app /app/app COPY ./app /app/app
COPY ./generate_math_exercises.py /app/ COPY ./generate_math_exercises.py /app/
# Change ownership of the app directory to the non-root user ENV PYTHONPATH=/app/site-packages
RUN chown -R appuser:appuser /app ENV PATH=/app/site-packages/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Set working directory
WORKDIR /app
# Switch to non-root user # Switch to non-root user
USER appuser USER appuser
@@ -40,9 +42,5 @@ USER appuser
# Expose port # Expose port
EXPOSE 8000 EXPOSE 8000
# Health check
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
# Run the application # Run the application
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]