mkdir flask-gunicorn-docker-boilerplate
cd flask-gunicorn-docker-boilerplate
Below is a complete, production-ready boilerplate for a Dockerized Flask application served by Gunicorn. It includes:
- A minimal Flask app (
app.py) with a health check endpoint.
requirements.txt with pinned dependencies.
Dockerfile using a multi-stage build for smaller image size.
docker-compose.yml for easy local development and production-like deployment.
.dockerignore and .gitignore for clean builds.
gunicorn.conf.py for Gunicorn configuration (e.g., workers, timeouts).
Makefile for common commands (build, run, lint, etc.).
Copy-paste the files below into the project root.
Folder Structure
flask-gunicorn-docker-boilerplate/
├── app/
│ └── __init__.py # Flask app factory pattern for scalability
├── app.py # Entry point (imports from app/)
├── gunicorn.conf.py # Gunicorn config
├── requirements.txt # Dependencies
├── Dockerfile # Multi-stage Docker build
├── docker-compose.yml # Orchestration
├── .dockerignore
├── .gitignore
└── Makefile # Convenience commands
Files
app/__init__.py (Flask app factory)
from flask import Flask
def create_app():
app = Flask(__name__)
@app.route('/')
def hello():
return {'message': 'Hello from Dockerized Flask + Gunicorn!'}
@app.route('/health')
def health():
return {'status': 'healthy'}, 200
return app
app.py (WSGI entry point)
from app import create_app
application = create_app()
if __name__ == '__main__':
application.run(host='0.0.0.0', port=8000, debug=True)
requirements.txt
Flask==3.0.3
Gunicorn==22.0.0
gunicorn.conf.py
# Gunicorn configuration for production
bind = "0.0.0.0:8000"
workers = 4 # Adjust based on CPU cores (2*cores + 1)
worker_class = "sync"
worker_connections = 1000
timeout = 30
keepalive = 2
max_requests = 1000
max_requests_jitter = 100
preload_app = True
accesslog = "-"
errorlog = "-"
loglevel = "info"
Dockerfile
# Multi-stage build for smaller final image
FROM python:3.12-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --user -r requirements.txt
FROM python:3.12-slim AS runtime
# Install runtime dependencies (minimal)
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=builder /root/.local /root/.local
COPY . .
# Create non-root user
RUN useradd --create-home appuser && chown -R appuser:appuser /app
USER appuser
EXPOSE 8000
CMD ["gunicorn", "--config", "gunicorn.conf.py", "app:application"]
docker-compose.yml
version: '3.8'
services:
web:
build: .
ports:
- "8000:8000"
environment:
- FLASK_ENV=production
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
.dockerignore
.git
.gitignore
README.md
.dockerignore
Makefile
tests/
*.pyc
__pycache__/
.pytest_cache/
.coverage
.env
.gitignore
.git/
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
.env
Makefile
.PHONY: build run lint test clean
build:
docker-compose build --no-cache
run:
docker-compose up -d
logs:
docker-compose logs -f
stop:
docker-compose down
lint:
poetry run flake8 . --max-line-length=120
test:
docker-compose run --rm web pytest
clean:
docker-compose down -v --remove-orphans
docker system prune -f
Quick Start
-
Build and run:
make build
make run
-
Test it:
curl http://localhost:8000/
# {"message": "Hello from Dockerized Flask + Gunicorn!"}
curl http://localhost:8000/health
# {"status": "healthy"}
-
View logs:
make logs
-
Stop:
make stop
Customization Notes
- Scaling: Use
docker-compose up --scale web=3 or Kubernetes for prod.
- Environment vars: Add
.env file and reference in docker-compose.yml.
- HTTPS/Reverse proxy: Add Nginx in Docker Compose for prod (e.g., via Traefik or separate service).
- Database: Extend
docker-compose.yml with Postgres/Redis services.
- CI/CD: Dockerfile is optimized for multi-stage builds in GitHub Actions/Docker Hub.
This boilerplate is lightweight (~150MB image), secure (non-root user), and ready for AWS ECS, Kubernetes, or local dev! 🚀