经验分享记录【经验分享】使用Gunicorn在Linux直接部署Flask服务
ELIX前言
之前也在ubuntu上部署过python项目,使用的是docker方式,虽然解决了依赖的问题,但维护起来很麻烦。
于是这次直接在虚拟环境上部署flask,意外的顺利运行起来了。
后来了解到Flask自带的服务器性能很差,官方也明文强烈禁止使用开发服务器运行项目,原因如下:
1.安全性。开发服务器未内置 Web 应用防火墙(WAF)、请求过滤等安全机制,易受 DDoS、SQL 注入等攻击。
2.性能。Flask 开发服务器基于 Werkzeug,默认只能同时处理一个请求,无法利用多核 CPU,无法扩展工作进程。
3.稳定性。无自动恢复机制,且长时间运行可能出现内存泄漏。
4.功能缺失。静态文件处理低效,缺乏请求日志、错误追踪等运维必需功能。
因此这次采用Gunicorn + Nginx的方式进行部署。
项目运行
1.先编译好Flask程序,本地运行成功后,使用第三方工具来获取requirements.txt,这里面包含了当前项目所有依赖包,方便服务器环境构建。
pip install pipreqs
pipreqs .
2.将项目上传到服务器,构建虚拟环境并测试项目运行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| sudo apt update sudo apt install python3-pip
sudo apt install python3-venv cd your_flask_project python3 -m venv project_name source venv/bin/activate
pip install flask pip install -r requirements.txt
export FLASK_APP=app.py export FLASK_ENV=development
flask run --host=0.0.0.0 --port=8088
|
3.运行成功后,即可进行生产环境迁移了。
生产环境部署
1.安装WSGI服务器依赖并尝试运行测试
1 2
| pip install flask gunicorn gunicorn --bind 0.0.0.0:5010 savehistory:app
|
2.创建系统服务配置sudo nano /etc/systemd/system/savehistory.service
1 2 3 4 5 6 7 8 9 10 11 12 13
| [Unit] Description=SaveHistory Flask App After=network.target
[Service] User=root
WorkingDirectory=/usr/amedia/end/AIend Environment="PATH=/usr/amedia/end/AIend/aiend/bin" ExecStart=/usr/amedia/end/AIend/aiend/bin/gunicorn --workers 2 --bind 0.0.0.0:5010 savehistory:app
[Install] WantedBy=multi-user.target
|
3.运行服务
1 2 3 4 5 6 7
| sudo systemctl daemon-reload sudo systemctl start savehistory sudo systemctl stop savehistory sudo systemctl enable savehistory
sudo systemctl status savehistory sudo journalctl -u savehistory -f
|
4.启用nginx代理sudo nano /etc/nginx/sites-available/savehistory
1 2 3 4 5 6 7 8 9 10
| server { listen 80; server_name 154.201.66.xxx;
location / { proxy_pass http://127.0.0.1:5010; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }
|
启动nginx
1 2
| sudo ln -s /etc/nginx/sites-enabled/savehistory sudo nginx -t && sudo systemctl reload nginx
|
完结收工