【部署实战】Nginx+Gunicorn 部署 Python Web 项目(详细步骤 + 踩坑总结)
·
上一篇是单纯在虚拟机里面部署一个网站,这个是用了nginx来部署的。网站的话你可以用ai随便跑一个,这个主要就是练练nginx部署,网站不重要。
一、环境准备
服务器系统:CentOS 7(其他 Linux 系统步骤类似)项目结构:以 Flask 项目为例,代码路径为 /home/ly/campus_crowdfunding
二、部署步骤(详细可执行)
步骤 1:安装依赖工具
bash
运行
# 安装Python依赖(Gunicorn)
pip install gunicorn
# 安装Nginx和进程管理工具Supervisor
sudo yum install nginx supervisor -y
步骤 2:配置 Gunicorn(用 Supervisor 管理进程)
Gunicorn 是 WSGI 服务器,负责运行 Python 应用,用 Supervisor 保证进程稳定运行。
2.1 编写 Supervisor 配置文件
bash
运行
vim /etc/supervisord.d/campus_crowdfunding.ini
粘贴以下内容(注意修改应用入口和项目路径):
ini
[program:campus_crowdfunding]
# 核心:Gunicorn启动命令(-b指定监听地址,"app:create_app()"是Flask应用工厂入口)
command=/root/.local/bin/gunicorn -w 4 -b 127.0.0.1:8000 "app:create_app()"
# 项目根目录
directory=/home/ly/campus_crowdfunding
# 运行用户
user=root
# 开机自动启动
autostart=true
# 进程崩溃后自动重启
autorestart=true
# 日志文件路径
stdout_logfile=/var/log/campus_crowdfunding.log
2.2 启动 Supervisor 并验证 Gunicorn
bash
运行
# 启动Supervisor服务
sudo systemctl start supervisord
# 查看Gunicorn进程状态(应为RUNNING)
sudo supervisorctl status campus_crowdfunding
# 检查8000端口是否被Gunicorn监听
netstat -tulnp | grep 8000
# 虚拟机内测试Gunicorn是否正常返回项目内容
curl http://127.0.0.1:8000
步骤 3:配置 Nginx(反向代理 + 静态文件处理)
Nginx 负责接收外部请求,转发给 Gunicorn,同时处理静态文件(CSS/JS/ 图片)。
3.1 编写 Nginx 配置文件
bash
运行
vim /etc/nginx/conf.d/campus_crowdfunding.conf
粘贴以下内容(修改虚拟机 IP和静态文件路径):
nginx
server {
# 监听默认HTTP端口(80)
listen 80;
# 虚拟机IP(或域名)
server_name 192.168.64.128;
# 处理静态文件(如项目的static目录)
location /static {
alias /home/ly/campus_crowdfunding/static;
# 静态文件缓存30天
expires 30d;
}
# 反向代理到Gunicorn的8000端口
location / {
proxy_pass http://127.0.0.1:8000;
# 传递请求头信息
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
3.2 验证 Nginx 配置并启动
bash
运行
# 检查Nginx配置语法是否正确
sudo nginx -t
# 启动Nginx服务
sudo systemctl start nginx
# 虚拟机内测试Nginx是否正常返回项目内容
curl http://127.0.0.1
步骤 4:解决环境限制(关键!)
CentOS 系统默认有 SELinux 和防火墙限制,必须处理否则会出现 502 / 连接失败。
4.1 允许 Nginx 连接网络(SELinux)
bash
运行
# 永久允许Nginx对外连接(解决502 Bad Gateway)
setsebool -P httpd_can_network_connect 1
4.2 开放 80 端口(防火墙)
bash
运行
# 永久开放80端口
sudo firewall-cmd --add-port=80/tcp --permanent
# 重新加载防火墙规则
sudo firewall-cmd --reload
步骤 5:本地访问
在本地浏览器输入:http://192.168.64.128(无需加端口,默认走 80)。
三、踩坑总结(必看!)
-
Gunicorn 应用入口错误
- 坑:配置成
app:app,但项目用的是应用工厂app:create_app() - 解决:严格对应项目的启动入口
- 坑:配置成
-
Nginx 反向代理地址不匹配
- 坑:
proxy_pass写了localhost:8000但 Gunicorn 监听的是127.0.0.1:8000 - 解决:保证
proxy_pass和 Gunicorn 的-b地址完全一致
- 坑:
-
SELinux 导致 502 错误
- 坑:Nginx 配置正确,但返回 502
- 解决:执行
setsebool -P httpd_can_network_connect 1开放网络权限
-
访问端口错误
- 坑:浏览器输入
192.168.64.128:8080(Nginx 监听的是 80 端口) - 解决:直接访问
http://192.168.64.128(默认 80 端口)
- 坑:浏览器输入
四、最终效果
本地浏览器输入虚拟机 IP 后,成功访问项目页面,静态文件加载正常,服务稳定运行。
更多推荐




所有评论(0)