Flask部署
Flask部署的二三事
当使用Flask作为开发语言的后端要上线之时,就会遇到部署的问题。众所周知,flask自带的开发服务器是不能用在生产环境的,正如官网这么说:
While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well. Some of the options available for properly running Flask in production are documented here.
常用的部署方案为使用uWSGI
使用WSGI服务器
uwsgi --http 127.0.0.1:5000 --module myproject:app
官网这么说:
For a more optimized setup, see configuring uWSGI and NGINX.
WSGI
作为web服务器,NGINX
作为代理服务器
配置WSGI服务器
常见的配置方案:创建config.ini
[uwsgi]
# uwsgi 启动时所使用的地址与端口
http-socket = 127.0.0.1:9001
# Flask目录
chdir = /home/xxxx/flask-app
# Flask 启动文件
wsgi-file = main.py
# Flask实例名字
callable = app
# 处理器数
processes = 4
# 线程数
threads = 2
#状态检和pid
stats=%(chdir)/uwsgi.status
pidfile=%(chdir)/uwsgi.pid
启动wsgi服务器
uwsgi --ini config.ini
uwsgi -d --ini config.ini #守护进程
uwsgi --reload uwsgi.pid #gracefully reload
配置NGINX代理服务器
http{
server {
listen 5001; #外部可访问端口
server_name xxxxx; #公网地址
location / {
include uwsgi_params;
proxy_pass http://127.0.0.1:9001; #wsgi端口
uwsgi_param UWSGI_PYHOME xxxx/venv; #flask 虚拟环境目录
uwsgi_param UWSGI_CHDIR xxxx; # flask目录
uwsgi_param UWSGI_SCRIPT main:app; # 指定启动程序
}
}
}
NGINX同时配置http和https
server {
listen 80;
listen 443 ssl;
server_name xxx;
ssl_certificate xxx.crt;
ssl_certificate_key xxx.key;
location / {
include uwsgi_params;
proxy_pass http://127.0.0.1:xxxx; #wsgi端口
}
}
然后重新加载nginx
nginx -s reload