Refactor Dockerfile for multi-stage build and add .dockerignore (#50)

This commit is contained in:
Xiao 2024-12-24 22:51:44 +01:00 committed by GitHub
parent dafe508fb8
commit 34b71e0ba2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 69 additions and 5 deletions

View file

@ -1,14 +1,37 @@
FROM python:3.12
# Build stage
FROM python:3.12-slim AS builder
WORKDIR /build
# Copy requirements first to leverage Docker cache
COPY requirements.txt .
# Install build dependencies and Python packages
RUN apt-get update \
&& apt-get install -y --no-install-recommends gcc python3-dev \
&& pip install --no-cache-dir --upgrade pip \
&& pip install --no-cache-dir --timeout 1000 -r requirements.txt \
&& rm -rf /var/lib/apt/lists/*
# Runtime stage
FROM python:3.12-slim
# Set Python environment variables
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
# Install git
RUN apt-get update \
&& apt-get install -y --no-install-recommends git \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Create a non-root user
RUN useradd -m -u 1000 appuser
COPY --from=builder /usr/local/lib/python3.12/site-packages/ /usr/local/lib/python3.12/site-packages/
COPY src/ ./
COPY requirements.txt ./
RUN pip install -r requirements.txt
# Change ownership of the application files
RUN chown -R appuser:appuser /app
@ -18,4 +41,4 @@ USER appuser
EXPOSE 8000
CMD ["uvicorn", "main:app", "--reload", "--host", "0.0.0.0"]
CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]