Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 36 additions & 21 deletions sample-docker-templates/flask/Dockerfile
Original file line number Diff line number Diff line change
@@ -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"]
CMD ["/app/start.sh"]