diff --git a/sample-docker-templates/flask/Dockerfile b/sample-docker-templates/flask/Dockerfile index 8261490866..ea21b6e777 100644 --- a/sample-docker-templates/flask/Dockerfile +++ b/sample-docker-templates/flask/Dockerfile @@ -1,40 +1,55 @@ -# Base Image - slim Python -FROM python:3.13-slim +# --- STAGE 1: Builder --- +FROM python:3.13-slim AS builder + +# Prevent Python from writing .pyc files and enable unbuffered logging +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + +WORKDIR /build + +# Install build dependencies +RUN apt-get update && \ + apt-get install -y --no-install-recommends gcc python3-dev build-essential libexpat1 && \ + rm -rf /var/lib/apt/lists/* + +# Install python dependencies into a local folder +COPY requirements.txt . +RUN pip install --no-cache-dir --prefix=/install -r requirements.txt + + +# --- STAGE 2: Runner --- +FROM python:3.13-slim AS runner # Environment settings -ENV PYTHONUNBUFFERED=1 LANG=C.UTF-8 +ENV PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + PATH="/home/nonroot/.local/bin:${PATH}" -# Set workdir WORKDIR /app -COPY requirements.txt requirements.txt - -# Install system dependencies and nginx, then install Python deps +# Install only essential runtime system libs (Nginx) RUN apt-get update && \ - apt-get install -y --no-install-recommends nginx gcc python3-dev musl-dev build-essential libexpat1 && \ - pip install --no-cache-dir -r requirements.txt && \ - apt-get purge -y --auto-remove gcc python3-dev musl-dev build-essential && \ + apt-get install -y --no-install-recommends nginx && \ rm -rf /var/lib/apt/lists/* -# Copy app code, configs, and start script +# Copy only the compiled python packages from the builder stage +COPY --from=builder /install /usr/local + +# Copy application code and configs COPY nginx.conf /etc/nginx/nginx.conf COPY app.py uwsgi.ini start.sh ./ RUN chmod +x start.sh -# Create non-root user and set permissions +# Security: Create non-root user RUN groupadd -g 2002 nonroot && \ useradd -u 2002 -g nonroot -s /bin/bash -m nonroot && \ - mkdir -p /tmp/nginx-logs && \ - chown -R nonroot:nonroot /app /tmp/nginx-logs + mkdir -p /tmp/nginx-logs /var/lib/nginx /var/log/nginx && \ + chown -R nonroot:nonroot /app /tmp/nginx-logs /var/lib/nginx /var/log/nginx -# Expose port 8080 -EXPOSE 8080 - -# Switch to non-root +# Switch to non-root user USER nonroot -# Stop signal for graceful shutdown +EXPOSE 8080 STOPSIGNAL SIGTERM -# Start server (migrations, superuser, gunicorn, nginx) -CMD ["/app/start.sh"] \ No newline at end of file +CMD ["/app/start.sh"]