Nginx 上部署一个 Python 服务的方法步骤
要在 Nginx 上部署一个 Python 服务,通常需要以下步骤:
1. 安装依赖
确保 Python 环境和依赖已安装:
```bash
sudo apt update
sudo apt install python3-flask
sudo apt install python3-pip
sudo apt install nginx
```
2. 使用 WSGI 服务器
生产环境通常使用 WSGI 服务器(如 Gunicorn)运行 Python 应用。
安装 Gunicorn
```bash
sudo apt install gunicorn
```
启动 Gunicorn
```bash
gunicorn --workers 3 --bind 0.0.0.0:5000 app:app
```
这将启动 3 个 worker 进程,监听 5000 端口。
3. 安装网络工具
apt install net-tools
apt install subversion
- net-tools 网络工具。
- subversion 文件管理工具。
4. 配置 Nginx
Nginx 作为反向代理,将请求转发给 Gunicorn。
创建 Nginx 配置文件
在 /etc/nginx/sites-available/
下创建配置文件,如 myapp
:
```nginx
server {
listen 80;
server_name your_domain_or_ip;
location /api {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /static/ {
alias /path/to/your/static/files/;
}
}
```
启用配置
测试配置,如无异常则启用配置:
```bash
sudo nginx -t
sudo systemctl reload nginx
```
5. 启动服务
确保 Gunicorn 和 Nginx 都在运行:
```bash
gunicorn --workers 3 --bind 0.0.0.0:5000 app:app
sudo systemctl start nginx
```
6. 访问服务
通过浏览器访问 http://your_domain_or_ip
,应该能看到 Flask 应用的响应。
总结
通过以上步骤,你可以在 Nginx 上成功部署 Python 服务。Nginx 作为反向代理,Gunicorn 作为 WSGI 服务器,确保服务高效稳定运行。