Flask+Gunicorn+Nginx 校园众筹项目部署全流程(生产环境)
一、项目背景
本项目为 Flask 工厂函数模式开发的校园众筹平台,需部署在 CentOS 系统中,实现 稳定运行 + 开机自启 + 多进程并发 的生产环境能力。
二、部署环境
- 操作系统:CentOS 7.x
- Python 版本:3.8+
- 核心组件:Gunicorn 23.0.0 + Nginx 1.20+
- 项目结构:Flask 工厂函数模式(
create_app启动)
三、部署核心步骤
1. 项目代码上传与准备
bash
运行
# 1. 创建项目目录
mkdir -p /var/www/html/campus_crowdfunding
# 2. 上传并解压项目代码到该目录
unzip campus_crowdfunding.zip -d /var/www/html/campus_crowdfunding
# 3. 进入项目目录
cd /var/www/html/campus_crowdfunding
# 4. 安装项目依赖
pip3 install -r requirements.txt
2. Gunicorn 启动适配(工厂函数模式)
bash
运行
# 测试启动(前台运行,验证逻辑)
/root/.local/bin/gunicorn --bind 127.0.0.1:8000 "app:create_app('development')"
# 验证:终端无报错,可通过 curl 访问
curl http://127.0.0.1:8000
注意:工厂函数模式必须用
"app:create_app('development')"作为启动参数,直接用app:app会报实例找不到错误。
3. Gunicorn 系统服务配置(实现开机自启)
3.1 创建服务文件
bash
运行
vi /etc/systemd/system/campus_crowdfunding.service
写入以下配置(含并发数 -w 4):
ini
[Unit]
Description=Campus Crowdfunding Gunicorn Service
After=network.target
[Service]
User=root
WorkingDirectory=/var/www/html/campus_crowdfunding
ExecStart=/root/.local/bin/gunicorn --bind 127.0.0.1:8000 -w 4 "app:create_app('development')"
Restart=on-failure
Environment="PATH=/usr/local/bin:/usr/bin:/root/.local/bin"
StandardOutput=append:/var/log/campus_crowdfunding.log
StandardError=append:/var/log/campus_crowdfunding.log
[Install]
WantedBy=multi-user.target
3.2 启动并设置自启
bash
运行
# 重载 systemd 配置
systemctl daemon-reload
# 启动服务
systemctl start campus_crowdfunding
# 设置开机自启
systemctl enable campus_crowdfunding
# 验证服务状态
systemctl status campus_crowdfunding
4. Nginx 反向代理配置
4.1 编辑 Nginx 站点配置
bash
运行
vi /etc/nginx/conf.d/default.conf
写入反向代理配置:
nginx
server {
listen 80;
server_name 192.168.226.128;
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;
}
# 静态文件映射(可选)
location /static/ {
root /var/www/html/campus_crowdfunding;
expires 30d;
}
}
4.2 验证并重启 Nginx
bash
运行
# 验证配置语法
nginx -t
# 重启 Nginx
systemctl restart nginx
# 验证 Nginx 自启状态
systemctl is-enabled nginx
四、常见问题排查
1. Gunicorn 启动失败:Address already in use
bash
运行
# 查找占用 8000 端口的进程
ss -tulnp | grep 8000
# 强制释放端口
fuser -k 8000/tcp
# 重启服务
systemctl restart campus_crowdfunding
2. 服务文件无法保存:E212: 无法打开并写入文件
bash
运行
# 切换到 root 用户或用 sudo 编辑
su root
# 或
sudo vi /etc/systemd/system/campus_crowdfunding.service
3. Gunicorn 服务启动后无进程
bash
运行
# 查看服务日志
journalctl -u campus_crowdfunding -l
# 或前台运行启动命令查错
/root/.local/bin/gunicorn --bind 127.0.0.1:8000 -w 4 "app:create_app('development')"
五、最终验证
- 进程验证 :
ps -ef | grep gunicorn显示 1 个 master + 4 个 worker 进程 - 访问验证 :
curl http://127.0.0.1返回Redirecting...页面 - 自启验证 :重启系统后,执行
systemctl status campus_crowdfunding确认服务自动启动
六、部署价值
本方案通过 systemd 托管 Gunicorn,实现了 开机自启、崩溃自愈、多进程并发 的生产级能力,解决了手动启动的临时性和不稳定性问题,同时适配 Flask 工厂函数模式的启动逻辑,保障了项目的长期稳定运行。