YouTip LogoYouTip

Flask Deployment

After development is complete, you need to deploy the Flask application to a production environment so real users can access it. This chapter introduces key steps and considerations from development to production. * * * ## Development Server vs Production Server > Important: Flask's built-in development server (flask run) is only suitable for development environments. It lacks the security, stability, and performance required for production environments. Production environments must use a professional WSGI server. | Feature | Flask Development Server | Production WSGI Server (Gunicorn/Waitress) | | --- | --- | --- | | Concurrency | Single-threaded (default) | Multi-process/multi-threaded/coroutine | | Security | Debug mode can execute code in browser | No debugging, secure and controllable | | Performance | Not optimized | Optimized for high concurrency | | Use Case | Local development, debugging | Online production environment | * * * ## Deployment Checklist Before deploying, make sure the following items are completed: ## Example # File path: app.py (Production environment related configuration check) import os app.config.update( # 1. Disable Debug mode (required!) DEBUG=False, # 2. Read secret key from environment variable (never hardcode) SECRET_KEY=os.environ.get("FLASK_SECRET_KEY",""), # 3. Configure Session Cookie security options SESSION_COOKIE_SECURE=True,# Only transmit via HTTPS SESSION_COOKIE_HTTPONLY=True,# Disable JavaScript access SESSION_COOKIE_SAMESITE="Lax",# Prevent CSRF attacks ) Complete checklist: | Check Item | Description | Risk Level | | --- | --- | --- | | DEBUG = False | Disable debug mode to prevent code leakage | Critical | | SECRET_KEY random and confidential | Session and flash depend on key signature | Critical | | SECRET_KEY read from environment variable | Don't hardcode, don't commit to Git | Critical | | Database password read from environment variable | Sensitive info not in code | Critical | | SESSION_COOKIE_SECURE = True | Only send Cookie under HTTPS | High | | Error pages don't expose stack traces | Use custom errorhandler | Medium | * * * ## Deploying with Waitress (Windows/macOS/Linux) Waitress is a pure Python WSGI server, cross-platform, easy to install: (.venv) $ pip install waitress ## Example # File path: run.py (Production environment startup script) from waitress import serve from app import create_app app = create_app() if __name__ =="__main__": # Start production server serve(app, host="0.0.0.0", port=8000, threads=4) # host="0.0.0.0" allows external access # threads=4 uses 4 threads to handle concurrent requests Startup: (.venv) $ python run.py Serving on http://0.0.0.0:8000 * * * ## Deploying with Gunicorn (Linux/macOS) Gunicorn is the most popular Python WSGI server in Linux environments, with excellent performance: (.venv) $ pip install gunicorn Start Gunicorn (specify application directly on command line): # Basic usage: 4 worker processes $ gunicorn -w 4 -b 0.0.0.0:8000 "app:create_app()"# Parameter description:# -w 4 : Start 4 worker processes (usually set to CPU cores Γ— 2 + 1)# -b 0.0.0.0:8000 : Listen on port 8000 of all network interfaces# "app:create_app()" : module name:factory function (same syntax as flask --app) Gunicorn worker type selection: | Worker Type | Use Case | Command | | --- | --- | --- | | sync (default) | CPU-intensive, low concurrency | gunicorn -w 4 app:app | | gevent | IO-intensive, high concurrency long connections | gunicorn -k gevent -w 4 app:app | | gthread | Medium concurrency, needs thread support | gunicorn --threads=2 -w 4 app:app | > Gunicorn does not support Windows. If you're deploying on Windows, use Waitress. * * * ## Using Nginx Reverse Proxy In production environments, Nginx is typically used as a reverse proxy in front of the WSGI server: * Nginx handles static files (CSS, JS, images), much more efficient than Python * Nginx provides HTTPS termination (SSL termination) * Nginx does load balancing, distributing requests to multiple backend workers ![Image 1: Flask Production Environment Deployment Architecture](#) A minimal Nginx configuration example: ## Example # File path: /etc/nginx/sites-available/tutorial server { listen 80; server_name www.; # Static files handled directly by Nginx location /static/{ alias/var/www/tutorial/static/; expires 30d; # Browser cache 30 days } # Other requests forwarded 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; } } Enable configuration and reload Nginx: $ sudo ln -s /etc/nginx/sites-available/tutorial /etc/nginx/sites-enabled/ $ sudo nginx -t # Check configuration syntax $ sudo systemctl reload nginx * * * ## Using systemd to Manage Services (Linux) Create a systemd service file to enable Flask application auto-start on boot and auto-restart after crashes: ## Example # File path: /etc/systemd/system/tutorial.service Description=TUTORIAL Flask Application After=network.target User=www-data WorkingDirectory=/var/www/tutorial # Automatically load environment variables from .env file on startup EnvironmentFile=-/var/www/tutorial/.env # Use Gunicorn to start the application ExecStart=/var/www/tutorial/.venv/bin/gunicorn -w 4-b 127.0.0.1:8000"app:create_app()" # Auto-restart after crash Restart=always RestartSec=5 WantedBy=multi-user.target Start and manage services: $ sudo systemctl daemon-reload # Reload configuration file $ sudo systemctl enable tutorial # Enable auto-start on boot $ sudo systemctl start tutorial # Start service $ sudo systemctl status tutorial # Check service status $ sudo journalctl -u tutorial -f # View logs in real-time * * * ## WSGI Server Quick Reference | Server | Platform | Features | Installation | | --- | --- | --- | --- | | Werkzeug (built-in) | All platforms | Development only, supports hot reload and debugger | Comes with Flask | | Waitress | All platforms | Pure Python, preferred for Windows | pip install waitress | | Gunicorn | Linux/macOS | Good performance, preferred for Linux, mature ecosystem | pip install gunicorn | | uWSGI | Linux/macOS | Full-featured, more complex configuration | pip install uwsgi | * * * ## Tutorial Summary Congratulations on completing all the content of the Flask Getting Started tutorial! Review what you've learned: | Chapter | Core Skills | | --- | --- | | Understanding Flask | Understand Flask's positioning and ecosystem | | Environment Setup | Create virtual environment, install dependencies | | First Application | Create minimal application, use flask run | | Routing System | URL mapping, variable rules, url_for, HTTP methods | | Request and Response | Read request data, construct various types of responses | | Template Rendering | Jinja2 syntax, template inheritance, XSS protection | | Static Files | Manage CSS/JS/images and other static resources | | Session and Cookie | User state persistence, Flash messages | | Configuration Management | Multi-environment configuration, environment variable loading | | Blueprint | Modular code organization, factory pattern | | Error Handling | Custom error pages, logging | | Database Integration | SQLite operations, g object for connection management | |
← Cmake Install SetupFlask Error β†’