三、增强网页的稳定性
- 使用 Gunicorn 代替 app.run(),实现中断重启
安装 Gunicorn 依赖(记得激活虚拟环境,见第一篇):
pip install flask gunicorn
终端在 app.py 的路径下(不含 app.py),启动 Gunicorn(这里是最简单的启动,仅作验证):
gunicorn -w 1 -b 0.0.0.0:8000 app:application
启动后可以正常访问网站即验证成功,进入下一步:开机自启与中断重启。
创建配置文件 /etc/systemd/system/flask-wsgi.service,写入配置:
[Unit]
Description=Flask WSGI service
After=network.target
[Service]
WorkingDirectory=app.py所在路径(不含app.py)
ExecStart=/虚拟环境路径/bin/gunicorn -w 2 -D -b 0.0.0.0:5000 app:application
Restart=always
RestartSec=3
User=root
[Install]
WantedBy=multi-user.target
启动此配置文件:
# 重新加载 Systemd 配置
sudo systemctl daemon-reload
# 启动 Flask 服务
sudo systemctl start flask-wsgi
# 设置开机自启
sudo systemctl enable flask-wsgi
检验崩溃重启:
# 手动杀死 Gunicorn 进程(模拟崩溃)
pkill -f gunicorn
后期网站配置更新后进行重载:
sudo systemctl restart flask-wsgi