Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Flask Deployment

Flask Deployment

After development is complete, the Flask application needs to be deployed to a production environment so real users can access it.

This chapter covers the key steps and precautions from development to production.


Development server vs. production server

Important: Flask's built-in development server (flask run) is only suitable for development. It lacks the security, stability, and performance required in production. Production must use a professional WSGI server.

Feature Flask development server Production WSGI server (Gunicorn/Waitress)
Concurrency Handling Single-threaded (default) Multi-process / multi-threaded / coroutine
Safety Debug mode allows code execution in the browser No debugging features, secure and controllable
Performance Not optimized Optimized for high concurrency
Applicable scenarios Local development and debugging Live production environment

Deployment checklist

Before deploying, make sure the following items are complete:

Example

File path: app.py (production-related configuration checks)

import

os

app.

config

.

update

(

   

1. Disable debug mode (mandatory!)

    DEBUG

=

False

,

   

2. Read the secret key from environment variables (never hard-code it)

    SECRET_KEY

=

os

.

environ

.

get

(

"FLASK_SECRET_KEY"

,

""

)

,

   

3. Configure session cookie security options

    SESSION_COOKIE_SECURE

=

True

,

 

Transmit only over HTTPS

    SESSION_COOKIE_HTTPONLY

=

True

,

Prohibit JavaScript access

    SESSION_COOKIE_SAMESITE

=

"Lax"

,

 

Prevent CSRF attacks

)

Full checklist:

Check item Description Risk level
DEBUG = False Disable debug mode to prevent code leakage Critical
SECRET_KEY is random and kept secret Sessions and flash rely on the secret key for signing Critical
SECRET_KEY is read from environment variables Not hard-coded, not committed to Git Critical
Database password is read from environment variables No sensitive information in code Critical
SESSION_COOKIE_SECURE = True Only send cookies over HTTPS High
Error pages do not expose stack traces Use a custom errorhandler Medium

Deploying with Waitress (Windows/macOS/Linux)

Waitress is a pure-Python WSGI server that is cross-platform and easy to install:



(.venv) $ pip install waitress

Example

File path: run.py (production startup script)

from

waitress

import

serve

from

app

import

create_app

app

=

create_app

(

)

if

name

==

"main"

:

   

Start the 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

Start:



(.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 on Linux, with excellent performance:



(.venv) $ pip install gunicorn

Start Gunicorn (specify the application directly on the 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 core count * 2 + 1)

# -b 0.0.0.0:8000 : Listen on port 8000 on all network interfaces

# "app:create_app()" : module name:factory function (same as flask --app syntax)

Gunicorn worker type selection:

Worker type Applicable scenarios Command
sync (default) CPU-intensive, low concurrency gunicorn -w 4 app:app
gevent IO-intensive, high concurrency with long connections gunicorn -k gevent -w 4 app:app
gthread Medium concurrency, requires thread support gunicorn --threads=2 -w 4 app:app

Gunicorn does not support Windows. If you are deploying on Windows, use Waitress。


Using Nginx as a reverse proxy

In production, Nginx is commonly used as a reverse proxy placed in front of the WSGI server:

Flask Production Environment Deployment Architecture

A minimal Nginx configuration example:

Example

File path: /etc/nginx/sites-available/runoob

server

{

    listen

80

;

    server_name runoob.com www.runoob.com;

   

Static files are handled directly by Nginx

    location

/

static

/

{

       

alias

/

var

/

www

/

runoob

/

static

/

;

        expires 30d;  

Browser cache for 30 days

   

}

   

Other requests are 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 the configuration and reload Nginx:



$ sudo ln -s /etc/nginx/sites-available/runoob /etc/nginx/sites-enabled/

$ sudo nginx -t          # 检查配置语法

$ sudo systemctl reload nginx


Managing services with systemd (Linux)

Create a systemd service file so the Flask application starts on boot and restarts automatically after a crash:

Example

File path: /etc/systemd/system/runoob.service

[

Unit

]

Description

=RUNOOB Flask Application

After

=network.target

[

Service

]

User

=www-data

WorkingDirectory

=

/

var

/

www

/

runoob

Automatically load environment variables from the .env file at startup

EnvironmentFile

=-

/

var

/

www

/

runoob

/

.env

Start the application with Gunicorn

ExecStart

=

/

var

/

www

/

runoob

/

.venv

/

bin

/

gunicorn

-w

4

-b

127.0.0.1:

8000

"app:create_app()"

Automatically restart after a crash

Restart

=always

RestartSec

=

5

[

Install

]

WantedBy

=multi-user.target

Start and manage the service:



$ sudo systemctl daemon-reload        # 重载配置文件

$ sudo systemctl enable runoob        # 设置开机自启

$ sudo systemctl start runoob         # 启动服务

$ sudo systemctl status runoob        # 查看服务状态

$ sudo journalctl -u runoob -f        # 实时查看日志


WSGI server quick reference

Server Platform Feature Installation
Werkzeug (built-in) Cross-platform For development only, supports hot reload and debugger Bundled with Flask
Waitress Cross-platform Pure Python, the top choice on Windows pip install waitress
Gunicorn Linux/macOS Good performance, the top choice on Linux, with a mature ecosystem pip install gunicorn
uWSGI Linux/macOS Feature-complete but relatively complex to configure pip install uwsgi

Tutorial summary

Congratulations on completing the entire Flask getting-started tutorial!

Let's review what you have learned:

Section Core skills
Getting to know Flask Understand Flask's positioning and ecosystem
Environment Preparation Create a virtual environment and install dependencies
Your first application Create a minimal application and use flask run
Routing System URL mapping, variable rules, url_for, HTTP methods
Requests and responses Read request data and construct various types of responses
Template rendering Jinja2 syntax, template inheritance, XSS protection
Static files Manage static assets such as CSS/JS/images
Sessions and cookies Maintaining user state, flash messages
Configuration management Multi-environment configuration, loading from environment variables
Blueprint Organize code modularly, factory pattern
Error handling Custom error pages, logging
Database integration SQLite operations, managing connections with the g object
Testing Testing routes and APIs with test_client and pytest
Deployment Gunicorn/Waitress + Nginx + systemd

Recommended directions for further study: