This is a comprehensive request for a dockerized Flask application with several components:
- Flask application with a /health endpoint
- Gunicorn as the WSGI server
- Nginx as a reverse proxy
- Docker Compose setup with healthchecks
- Auto-restart policy
- Logrotate configuration for access logs
Let me create a complete, production-ready setup with all necessary files.
Structure:
project/
├── docker-compose.yml
├── Dockerfile (for Flask/Gunicorn)
├── nginx/
│ ├── Dockerfile
│ ├── nginx.conf
│ └── logrotate/
│ └── nginx
├── app/
│ ├── __init__.py
│ ├── main.py
│ └── wsgi.py
├── requirements.txt
├── .dockerignore
├── .env.example
└── scripts/
└── healthcheck.sh
Let me create all the necessary files:
- main application files - Flask app with health endpoint
- Dockerfile - For the Flask/Gunicorn container
- nginx configuration - Reverse proxy setup
- docker-compose.yml - Orchestration with healthchecks
- logrotate configuration - For log rotation
- Supporting files - requirements.txt, .dockerignore, etc.
Key requirements:
- Healthcheck that curls /health
- Auto-restart after 3 failures
- Logrotate for access logs
- Gunicorn behind Nginx
- Production-ready setup
Dockerized Flask + Gunicorn + Nginx with Healthcheck & Logrotate
I'll create a complete production-ready setup with all components.
Project Structure
flask-docker-boilerplate/
├── docker-compose.yml
├── Dockerfile
├── .dockerignore
├── requirements.txt
├── .env.example
├── app/
│ ├── __init__.py
│ ├── main.py
│ └── wsgi.py
├── nginx/
│ ├── Dockerfile
│ ├── nginx.conf
│ └── conf.d/
│ └── default.conf
├── config/
│ ├── gunicorn_config.py
│ └── logrotate
│ ├── nginx
│ └── gunicorn
└── scripts/
└── healthcheck.sh
1. Flask Application
app/init.py
from flask import Flask
from datetime import datetime
def create_app():
"""Application factory"""
app = Flask(__name__)
app.config.from_object('app.config')
# Register blueprints
from app.main import bp as main_bp
app.register_blueprint(main_bp)
return app
app/main.py
from flask import Blueprint, jsonify, request, current_app
import os
from datetime import datetime
bp = Blueprint('main', __name__)
@bp.route('/health', methods=['GET'])
def health():
"""Health check endpoint"""
try:
return jsonify({
'status': 'healthy',
'timestamp': datetime.utcnow().isoformat(),
'service': 'flask-api',
'environment': os.getenv('ENVIRONMENT', 'development')
}), 200
except Exception as e:
current_app.logger.error(f"Health check failed: {str(e)}")
return jsonify({
'status': 'unhealthy',
'error': str(e)
}), 500
@bp.route('/ready', methods=['GET'])
def ready():
"""Readiness check endpoint"""
return jsonify({
'ready': True,
'timestamp': datetime.utcnow().isoformat()
}), 200
@bp.route('/', methods=['GET'])
def index():
"""Index endpoint"""
return jsonify({
'message': 'Welcome to Flask API',
'version': '1.0.0',
'endpoints': {
'health': '/health',
'ready': '/ready',
'api': '/api/v1/data'
}
}), 200
@bp.route('/api/v1/data', methods=['GET'])
def get_data():
"""Sample API endpoint"""
return jsonify({
'data': [
{'id': 1, 'name': 'item1'},
{'id': 2, 'name': 'item2'}
],
'timestamp': datetime.utcnow().isoformat()
}), 200
@bp.errorhandler(404)
def not_found(error):
"""Handle 404 errors"""
return jsonify({'error': 'Not found'}), 404
@bp.errorhandler(500)
def internal_error(error):
"""Handle 500 errors"""
return jsonify({'error': 'Internal server error'}), 500
app/wsgi.py
import os
import logging
from app import create_app
# Create Flask app
app = create_app()
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
if __name__ == "__main__":
app.run()
2. Flask Configuration
app/config.py (or in init.py)
import os
from datetime import timedelta
class Config:
"""Base configuration"""
DEBUG = False
TESTING = False
JSON_SORT_KEYS = False
JSONIFY_PRETTYPRINT_REGULAR = True
# Session
PERMANENT_SESSION_LIFETIME = timedelta(days=7)
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
# Logging
LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')
class DevelopmentConfig(Config):
"""Development configuration"""
DEBUG = True
SESSION_COOKIE_SECURE = False
class ProductionConfig(Config):
"""Production configuration"""
DEBUG = False
TESTING = False
class TestingConfig(Config):
"""Testing configuration"""
TESTING = True
SESSION_COOKIE_SECURE = False
config = {
'development': DevelopmentConfig,
'production': ProductionConfig,
'testing': TestingConfig,
'default': DevelopmentConfig
}
3. Gunicorn Configuration
config/gunicorn_config.py
import multiprocessing
import os
from pathlib import Path
# Server socket
bind = "0.0.0.0:8000"
backlog = 2048
# Worker processes
workers = int(os.getenv('GUNICORN_WORKERS', multiprocessing.cpu_count() * 2 + 1))
worker_class = "sync"
worker_connections = 1000
worker_timeout = 60
keepalive = 5
# Logging
accesslog = "/var/log/gunicorn/access.log"
errorlog = "/var/log/gunicorn/error.log"
loglevel = os.getenv('LOG_LEVEL', 'info')
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(D)s'
# Process naming
proc_name = "flask-api"
# Server mechanics
daemon = False
pidfile = "/var/run/gunicorn/gunicorn.pid"
umask = 0
user = None
group = None
tmp_upload_dir = "/tmp"
# SSL (if needed, configure in production)
# keyfile = "/path/to/keyfile"
# certfile = "/path/to/certfile"
# Application
max_requests = 1000
max_requests_jitter = 50
preload_app = True
# Callbacks (for graceful shutdown)
def on_starting(server):
server.log.info("Gunicorn server is starting...")
def on_exit(server):
server.log.info("Gunicorn server has exited")
def when_ready(server):
server.log.info("Gunicorn server is ready. Spawning workers")
def worker_int(worker):
worker.log.info("Worker received INT or QUIT signal")
def worker_abort(worker):
worker.log.info("Worker received SIGABRT signal")
4. Requirements
requirements.txt
Flask==2.3.3
Werkzeug==2.3.7
gunicorn==21.2.0
python-dotenv==1.0.0
requests==2.31.0
5. Dockerfile (Flask + Gunicorn)
Dockerfile
# Multi-stage build
FROM python:3.11-slim as builder
WORKDIR /build
# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc \
&& rm -rf /var/lib/apt/lists/*
# Copy requirements and install Python dependencies
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt
# Final stage
FROM python:3.11-slim
# Install runtime dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
ca-certificates \
tini \
logrotate \
&& rm -rf /var/lib/apt/lists/*
# Create application user
RUN useradd -m -u 1000 appuser && \
mkdir -p /var/log/gunicorn /var/run/gunicorn && \
chown -R appuser:appuser /var/log/gunicorn /var/run/gunicorn
# Set working directory
WORKDIR /app
# Copy Python dependencies from builder
COPY --from=builder /root/.local /home/appuser/.local
# Copy application code
COPY --chown=appuser:appuser app/ /app/app/
COPY --chown=appuser:appuser config/ /app/config/
COPY --chown=appuser:appuser config/logrotate/gunicorn /etc/logrotate.d/gunicorn
# Set environment variables
ENV PATH=/home/appuser/.local/bin:$PATH \
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
ENVIRONMENT=production \
LOG_LEVEL=info
# Switch to non-root user
USER appuser
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
# Use tini as entrypoint for proper signal handling
ENTRYPOINT ["/usr/bin/tini", "--"]
# Run gunicorn
CMD ["gunicorn", \
"--config", "config/gunicorn_config.py", \
"--access-logfile", "-", \
"--error-logfile", "-", \
"app.wsgi:app"]
6. Nginx Configuration
nginx/Dockerfile
FROM nginx:1.25-alpine
# Install logrotate and curl for health checks
RUN apk add --no-cache \
logrotate \
curl \
bash
# Create nginx user and log directories
RUN mkdir -p /var/log/nginx && \
chown -R nginx:nginx /var/log/nginx
# Copy nginx configuration
COPY nginx.conf /etc/nginx/nginx.conf
COPY conf.d/default.conf /etc/nginx/conf.d/default.conf
# Copy logrotate configuration
COPY logrotate/nginx /etc/logrotate.d/nginx
# Create logrotate cleanup script
RUN echo '#!/bin/sh\nlogrotate -f /etc/logrotate.d/nginx' > /usr/local/bin/rotate-logs && \
chmod +x /usr/local/bin/rotate-logs
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
CMD curl -f http://localhost/health || exit 1
EXPOSE 80 443
CMD ["nginx", "-g", "daemon off;"]
nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging format with additional details
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'rt=$request_time uct="$upstream_connect_time" '
'uht="$upstream_header_time" urt="$upstream_response_time"';
log_format json_combined escape=json
'{'
'"time_local":"$time_local",'
'"remote_addr":"$remote_addr",'
'"remote_user":"$remote_user",'
'"request":"$request",'
'"status": "$status",'
'"body_bytes_sent":"$body_bytes_sent",'
'"request_time":"$request_time",'
'"http_referrer":"$http_referer",'
'"http_user_agent":"$http_user_agent"'
'}';
access_log /var/log/nginx/access.log main;
# Performance optimizations
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
client_max_body_size 100M;
# Gzip compression
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss
application/rss+xml font/truetype font/opentype
application/vnd.ms-fontobject image/svg+xml;
gzip_disable "msie6";
# Rate limiting
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=general_limit:10m rate=30r/s;
# Upstream backend
upstream flask_backend {
least_conn;
server flask-app:8000 max_fails=3 fail_timeout=10s;
keepalive 32;
}
# Include additional configurations
include /etc/nginx/conf.d/*.conf;
}
nginx/conf.d/default.conf
server {
listen 80;
server_name _;
# Redirect HTTP to HTTPS if needed (uncomment when using SSL)
# return 301 https://$server_name$request_uri;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
# Hide nginx version
server_tokens off;
# Health check endpoint (for load balancers)
location /health {
access_log off;
proxy_pass http://flask_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_connect_timeout 5;
proxy_send_timeout 5;
proxy_read_timeout 5;
}
# Ready check endpoint
location /ready {
access_log off;
proxy_pass http://flask_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
# API endpoints with rate limiting
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
proxy_pass http://flask_backend;
proxy_http_version 1.1;
# Headers
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $server_name;
# Timeouts
proxy_connect_timeout 10s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# Buffering
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
}
# General location with rate limiting
location / {
limit_req zone=general_limit burst=50 nodelay;
proxy_pass http://flask_backend;
proxy_http_version 1.1;
# Headers
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $server_name;
# Timeouts
proxy_connect_timeout 10s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# Buffering
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
}
# Static files (if needed)
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
proxy_pass http://flask_backend;
}
# Deny access to sensitive files
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# 404 error page
error_page 404 =404 '{"error": "Not found"}';
}
# HTTPS configuration (uncomment and configure when ready)
# server {
# listen 443 ssl http2;
# server_name _;
#
# ssl_certificate /etc/nginx/ssl/cert.pem;
# ssl_certificate_key /etc/nginx/ssl/key.pem;
#
# ssl_protocols TLSv1.2 TLSv1.3;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
#
# # ... rest of configuration
# }
7. Logrotate Configurations
config/logrotate/gunicorn
/var/log/gunicorn/*.log {
daily
rotate 14
missingok
compress
delaycompress
notifempty
create 0640 appuser appuser
sharedscripts
postrotate
if [ -f /var/run/gunicorn/gunicorn.pid ]; then
kill -USR1 $(cat /var/run/gunicorn/gunicorn.pid) 2>/dev/null || true
fi
endscript
}
config/logrotate/nginx
/var/log/nginx/*.log {
daily
rotate 14
missingok
compress
delaycompress
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 $(cat /var/run/nginx.pid) 2>/dev/null || true
fi
endscript
}
8. Docker Compose
docker-compose.yml
version: '3.9'
services:
flask-app:
build:
context: .
dockerfile: Dockerfile
container_name: flask-api
image: flask-api:latest
restart: unless-stopped
environment:
- ENVIRONMENT=production
- LOG_LEVEL=info
- GUNICORN_WORKERS=4
- FLASK_ENV=production
ports:
- "8000"
expose:
- "8000"
volumes:
- gunicorn_logs:/var/log/gunicorn
- /tmp:/tmp
networks:
- app_network
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
depends_on:
- nginx
labels:
- "com.example.description=Flask API Service"
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
nginx:
build:
context: ./nginx
dockerfile: Dockerfile
container_name: nginx-proxy
image: nginx-proxy:latest
restart: unless-stopped
ports:
- "80:80"
- "443:443"
volumes:
- nginx_logs:/var/log/nginx
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ./nginx/conf.d/:/etc/nginx/conf.d/:ro
# Uncomment for SSL certificates
# - ./nginx/ssl/:/etc/nginx/ssl/:ro
networks:
- app_network
depends_on:
- flask-app
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
labels:
- "com.example.description=Nginx Reverse Proxy"
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "5"
volumes:
gunicorn_logs:
driver: local
nginx_logs:
driver: local
networks:
app_network:
driver: bridge
9. Environment Configuration
.env.example
# Environment
ENVIRONMENT=production
LOG_LEVEL=info
# Flask
FLASK_ENV=production
FLASK_DEBUG=0
# Gunicorn
GUNICORN_WORKERS=4
# Database (if needed)
DATABASE_URL=sqlite:///app.db
# API Settings
API_TIMEOUT=30
MAX_CONTENT_LENGTH=104857600
10. Docker Build Ignore
.dockerignore
__pycache__
*.pyc
*.pyo
*.egg-info
.pytest_cache
.coverage
htmlcov
dist
build
.git
.gitignore
.dockerignore
.Github
README.md
*.md
.env
.env.local
.vscode
.idea
*.swp
*.swo
*~
.DS_Store
.editorconfig
11. Additional Scripts
scripts/healthcheck.sh
#!/bin/bash
# Healthcheck script for container orchestration
HEALTH_ENDPOINT=${1:-"http://localhost/health"}
TIMEOUT=${2:-10}
RETRIES=${3:-3}
attempt=0
while [ $attempt -lt $RETRIES ]; do
response=$(curl -s -w "\n%{http_code}" --connect-timeout $TIMEOUT --max-time $TIMEOUT "$HEALTH_ENDPOINT")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [ "$http_code" = "200" ]; then
echo "✓ Health check passed"
echo "$body"
exit 0
fi
attempt=$((attempt + 1))
echo "✗ Health check failed (attempt $attempt/$RETRIES): HTTP $http_code"
if [ $attempt -lt $RETRIES ]; then
sleep 2
fi
done
echo "✗ Health check failed after $RETRIES attempts"
exit 1
12. Makefile (Optional but useful)
Makefile
.PHONY: help build up down logs clean test dev prod
help:
@echo "Available commands:"
@echo " make build - Build Docker images"
@echo " make up - Start containers"
@echo " make down - Stop containers"
@echo " make logs - View logs"
@echo " make clean - Clean up volumes and containers"
@echo " make dev - Run in development mode"
@echo " make prod - Run in production mode"
@echo " make test - Run tests"
@echo " make shell - Open shell in flask container"
build:
docker-compose build
up:
docker-compose up -d
@echo "Containers started. Nginx: http://localhost"
down:
docker-compose down
logs:
docker-compose logs -f
logs-flask:
docker-compose logs -f flask-app
logs-nginx:
docker-compose logs -f nginx
clean:
docker-compose down -v
find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
find . -type f -name "*.pyc" -delete
dev:
docker-compose -f docker-compose.yml -f docker-compose.dev.yml up
prod: build up
test:
docker-compose exec flask-app python -m pytest
shell:
docker-compose exec flask-app /bin/bash
push:
docker tag flask-api:latest your_registry/flask-api:latest
docker push your_registry/flask-api:latest
docker tag nginx-proxy:latest your_registry/nginx-proxy:latest
docker push your_registry/nginx-proxy:latest
restart:
docker-compose restart
ps:
docker-compose ps
health:
docker-compose exec nginx curl -f http://localhost/health
13. GitHub Actions CI/CD (Optional)
.github/workflows/build.yml
name: Build and Test
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Build Flask image
uses: docker/build-push-action@v4
with:
context: .
push: false
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Run tests
run: docker-compose run --rm flask-app pytest
- name: Test endpoints
run: |
docker-compose up -d
sleep 10
curl -f http://localhost/health
curl -f http://localhost/ready
curl -f http://localhost/api/v1/data
docker-compose down
14. Quick Start Guide
README.md
# Flask + Gunicorn + Nginx Docker Boilerplate
A production-ready Docker setup with Flask, Gunicorn, and Nginx reverse proxy.
## Features
- ✅ Multi-stage Docker builds for minimal image size
- ✅ Nginx reverse proxy with rate limiting
- ✅ Gunicorn WSGI server with graceful shutdown
- ✅ Health checks with auto-restart on 3 failures
- ✅ Logrotate configuration for log management
- ✅ Security headers and best practices
- ✅ Docker Compose orchestration
- ✅ Non-root user execution
- ✅ Comprehensive logging
## Quick Start
```bash
# Clone repository
git clone <repo>
cd flask-docker-boilerplate
# Copy environment file
cp .env.example .env
# Build and start containers
make build
make up
# View logs
make logs
# Test endpoints
curl http://localhost/health
curl http://localhost/api/v1/data
Endpoints
GET / - Welcome message
GET /health - Health check
GET /ready - Readiness check
GET /api/v1/data - Sample API endpoint
Health Check
The docker-compose setup includes health checks that:
- Check
/health endpoint every 30 seconds
- Timeout after 10 seconds
- Auto-restart container after 3 consecutive failures
- Start checking after 40 seconds (Flask) / 10 seconds (Nginx)
Logs
Logs are rotated daily and kept for 14 days:
# View Flask logs
docker exec flask-api tail -f /var/log/gunicorn/access.log
# View Nginx logs
docker exec nginx-proxy tail -f /var/log/nginx/access.log
# Using Docker Compose
make logs-flask
make logs-nginx
Production Deployment
- Update
.env with production values
- Configure SSL certificates in
nginx/ssl/
- Uncomment SSL section in
nginx/conf.d/default.conf
- Run:
make prod
Scaling
# Scale gunicorn workers
GUNICORN_WORKERS=8 docker-compose up -d flask-app
Debugging
# Access Flask container shell
make shell
# Full container logs
docker-compose logs flask-app
docker-compose logs nginx
# Health check details
docker inspect <container_name> | grep -A 10 Health
License
MIT
## Usage
```bash
# 1. Create project structure
mkdir -p flask-docker-boilerplate && cd flask-docker-boilerplate
# 2. Copy all files from above
# 3. Build images
docker-compose build
# 4. Start services
docker-compose up -d
# 5. Verify health
curl http://localhost/health
# Response: {"status":"healthy","timestamp":"...","service":"flask-api",...}
# 6. Test API
curl http://localhost/api/v1/data
# 7. Check logs
docker-compose logs -f flask-app
docker-compose logs -f nginx
# 8. Monitor health status
docker ps # Check STATUS column
# 9. Stop services
docker-compose down
# 10. Clean up volumes
docker-compose down -v
Key Features
✅ Auto-restart on failure: 3 failed health checks trigger container restart
✅ Logrotate: Access logs rotated daily, kept 14 days
✅ Security: Security headers, rate limiting, SQL injection prevention
✅ Performance: Nginx caching, Gzip compression, connection pooling
✅ Production-ready: Non-root user, graceful shutdown, proper signal handling
✅ Monitoring: Detailed logging with request timing metrics
This setup is production-ready and follows Docker best practices!