Flask’s built-in development server is not suitable for production — it’s single-threaded, has no process management, and exposes raw Python tracebacks. A production Flask deployment uses Gunicorn as the WSGI application server and Nginx as the reverse proxy. This guide covers the complete setup on Ubuntu 22.04.
📋 Table of Contents
- Architecture Overview
- Step 1: Server Setup
- Step 2: Deploy Application
- Step 3: Configure Gunicorn
- Step 4: systemd Service
- Step 5: Nginx Configuration
- Step 6: SSL with Let's Encrypt
- Step 7: Deployment Workflow
- Environment Variables (Production)
- Monitoring and Logs
- Frequently Asked Questions
- Conclusion
🔑 Key Takeaway
Flask’s built-in development server is not suitable for production — it’s single-threaded, has no process management, and exposes raw Python tracebacks. A production Flask deployment uses Gunicorn as the WSGI application server and Nginx as the re…
Architecture Overview
Internet → Nginx (port 80/443, SSL termination, static files)
↓
Gunicorn (port 8000, multiple worker processes)
↓
Flask Application (WSGI app)
Step 1: Server Setup
sudo apt update && sudo apt upgrade -y
sudo apt install -y python3-pip python3-venv nginx certbot python3-certbot-nginx
# Create application user (don't run as root)
sudo useradd -m -s /bin/bash flaskapp
sudo mkdir /var/www/myapp
sudo chown flaskapp:flaskapp /var/www/myapp
Step 2: Deploy Application
sudo su - flaskapp
cd /var/www/myapp
# Clone your repo
git clone https://github.com/youruser/myapp.git .
# Create virtual environment
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
pip install gunicorn
Your Flask app entry point (app.py or wsgi.py):
# wsgi.py
from myapp import create_app
app = create_app()
if __name__ == '__main__':
app.run()
Step 3: Configure Gunicorn
# /var/www/myapp/gunicorn.conf.py
bind = "127.0.0.1:8000"
workers = 4 # rule: (2 × CPU cores) + 1
worker_class = "gthread" # threaded worker for I/O-bound apps
threads = 2
timeout = 120
keepalive = 5
max_requests = 1000 # restart worker after N requests (prevents memory leaks)
max_requests_jitter = 50 # randomize restart to avoid thundering herd
errorlog = "/var/log/gunicorn/error.log"
accesslog = "/var/log/gunicorn/access.log"
loglevel = "info"
preload_app = True # load app before forking workers (faster startup)
sudo mkdir /var/log/gunicorn
sudo chown flaskapp:flaskapp /var/log/gunicorn
# Test gunicorn starts correctly
cd /var/www/myapp
source venv/bin/activate
gunicorn --config gunicorn.conf.py wsgi:app
Step 4: systemd Service
# /etc/systemd/system/myapp.service
[Unit]
Description=Gunicorn daemon for myapp
After=network.target
[Service]
User=flaskapp
Group=flaskapp
WorkingDirectory=/var/www/myapp
Environment="PATH=/var/www/myapp/venv/bin"
EnvironmentFile=/var/www/myapp/.env
ExecStart=/var/www/myapp/venv/bin/gunicorn --config gunicorn.conf.py wsgi:app
ExecReload=/bin/kill -s HUP $MAINPID
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start myapp
sudo systemctl enable myapp # start on boot
sudo systemctl status myapp # verify running
Step 5: Nginx Configuration
# /etc/nginx/sites-available/myapp
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
# Static files served directly by Nginx (much faster than Gunicorn)
location /static {
alias /var/www/myapp/static;
expires 30d;
add_header Cache-Control "public, immutable";
}
# Proxy everything else to Gunicorn
location / {
proxy_pass http://127.0.0.1:8000;
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_read_timeout 120s;
proxy_connect_timeout 10s;
# Security headers
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header Referrer-Policy "strict-origin-when-cross-origin";
}
# Upload size limit
client_max_body_size 16M;
}
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
Step 6: SSL with Let’s Encrypt
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
# Verify auto-renewal
sudo certbot renew --dry-run
Certbot automatically modifies your Nginx config to add SSL, redirect HTTP to HTTPS, and adds a cron job for certificate renewal.
Step 7: Deployment Workflow
# After code changes:
cd /var/www/myapp
git pull origin main
source venv/bin/activate
pip install -r requirements.txt # if dependencies changed
flask db upgrade # if migrations exist
# Zero-downtime reload (sends SIGHUP to Gunicorn master)
sudo systemctl reload myapp
# Full restart (brief downtime)
sudo systemctl restart myapp
Environment Variables (Production)
# /var/www/myapp/.env (permissions: 600, owned by flaskapp)
FLASK_ENV=production
SECRET_KEY=your-long-random-secret-key
DATABASE_URL=postgresql://user:pass@localhost/mydb
REDIS_URL=redis://localhost:6379/0
sudo chmod 600 /var/www/myapp/.env
sudo chown flaskapp:flaskapp /var/www/myapp/.env
Monitoring and Logs
# View logs
sudo journalctl -u myapp -f # systemd logs
sudo tail -f /var/log/gunicorn/error.log
sudo tail -f /var/log/nginx/access.log
# Check worker processes
sudo systemctl status myapp
pgrep -a gunicorn
Frequently Asked Questions
Q: How many Gunicorn workers should I use?
A: (2 × CPU cores) + 1 is the standard formula. For a 2-core VPS: 5 workers. More workers = more memory usage. Use gthread worker class with 2-4 threads for I/O-bound Flask apps.
Q: Gunicorn vs uWSGI?
A: Gunicorn for simplicity and Python ecosystem familiarity. uWSGI is faster but more complex to configure. For most Flask applications, Gunicorn performs identically and is far simpler to set up and maintain.
Q: Why not just run Flask directly on port 80?
A: Nginx handles SSL termination, static file serving (much faster), connection queueing, load balancing, security headers, and request buffering. Running Flask directly means one process per connection, no SSL optimization, and slow static file serving.
Q: How do I handle zero-downtime deploys?
A: systemctl reload myapp sends SIGHUP to Gunicorn master, which gracefully replaces workers with new ones while finishing in-flight requests. New code loads in new workers without dropping connections.
Q: Should I use Docker instead?
A: Docker is excellent for multi-service apps (with Docker Compose) and for consistency across environments. For a single Flask app on a VPS, systemd + Gunicorn + Nginx is simpler, uses less memory, and is easier to debug. Both approaches work well.
Conclusion
The Flask production stack of Gunicorn + Nginx + systemd is battle-tested, well-documented, and appropriate for applications serving thousands of requests per minute on modest VPS hardware. This setup handles: multiple worker processes for concurrency, graceful zero-downtime reloads, SSL termination, static file optimization, and process auto-restart on failure. It’s everything you need to serve a production Flask application reliably.
📚 You might also like
🔗 Share this article




✍️ Leave a Comment