Containerizing Python applications with Docker (Part 2): Flask Dockerfile
Building on **Docker basics**, Flask apps need HTTP servers suited for multiprocess production (gunicorn, waitress, Hypercorn ASGI equivalents) rather than flask run defaults.
📚 Prerequisites
- Completed Series 14 (Flask) or equivalent familiarity.
🎯 What you'll learn
- Run Flask behind
gunicorninside Docker. - Expose configurable workers and ports for orchestrators like Kubernetes.
Example Dockerfile targeting WSGI
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PORT=8000
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
RUN pip install gunicorn
CMD ["sh", "-c", "gunicorn -w 4 -b 0.0.0.0:${PORT} app.wsgi:app"]
Assume app/wsgi.py exposes app as the WSGI callable.
Health checks & signals
Compose/Kubernetes manifests should define health checks hitting /healthz so rolling deploys discard broken pods.
Use docker stop gracefully—ensure base images propagate SIGTERM to worker processes (gunicorn handles this with --graceful-timeout).
💡 Key takeaways
- Containers wrap processes, not magically scaled databases—migrate stateful services separately.
➡️ Next steps
Compare hosted platforms in Cloud deployment (Heroku, AWS, overview).