如何在服务器 Ubuntu 22.04 上部署 FastAPI + Uvicorn + Nginx 生产级 Python Web 服务指南
本文从基础环境准备、部署架构设计、性能调优、安全配置到监控指标采集,全流程讲解如何在 Ubuntu 22.04 服务器 上构建一个可用于生产环境的 FastAPI + Uvicorn + Nginx Python Web 服务平台。A5数据重点聚焦实战细节、系统参数配置、性能评测与问题排查方法,适合有一定 Linux / 网络 / Python 经验的开发与运维人员阅读。
一、目标架构与适用场景
在生产环境下,单纯使用 Uvicorn 监听外部请求存在性能和安全风险,因此我们采用如下部署架构:
Internet │ ▼ Nginx (反向代理 + SSL/TLS) │ proxy_pass ▼ Uvicorn Workers (基于 uvloop + Gunicorn 管理) │ FastAPI Application │ PostgreSQL / Redis / 后端微服务 适用场景包括:
- 高并发 API 服务
- 微服务架构中 HTTP 接口部署
- 需要TLS/HTTPS安全访问的生产环境
二、香港服务器www.a5idc.com硬件与系统建议
| 项目 | 推荐配置 | 说明 |
|---|---|---|
| CPU | 4 核及以上 | 并发请求更稳定 |
| 内存 | 8GB 以上 | Python GC + 缓存空间 |
| 磁盘 | NVMe 150GB 以上 | 快速日志写入 |
| 网络 | 公网带宽 100Mbps | API 对外访问 |
| 系统 | Ubuntu 22.04 LTS | 最新稳定版 |
外网访问建议部署具有 DDoS 防护的 BGP 线路服务器,例如 CN2 / 电信直连方案,以降低网络抖动和丢包率。
三、系统初始化与依赖安装
3.1 系统更新
sudoapt update &&sudoapt upgrade -y sudoreboot3.2 安装 Python 环境与必备工具
# 安装 Python3.10sudoaptinstall -y python3.10 python3.10-venv python3.10-dev python3-pip build-essential # 常用工具sudoaptinstall -y nginx ufw git3.3 建立虚拟环境
进入应用目录 /opt/fastapi_app:
sudomkdir -p /opt/fastapi_app sudochown$USER:$USER /opt/fastapi_app cd /opt/fastapi_app python3.10 -m venv venv source venv/bin/activate 四、应用代码结构与示例
4.1 最简 FastAPI 项目结构
fastapi_app/ ├── app/ │ ├── main.py │ ├── api/ │ │ └── v1.py ├── requirements.txt └── logging.conf 4.2 示例代码
app/main.py
from fastapi import FastAPI import uvicorn app = FastAPI(title="示例 FastAPI 服务")@app.get("/health")defhealth_check():return{"status":"OK"}@app.get("/items/{item_id}")defread_item(item_id:int, q:str=None):return{"item_id": item_id,"q": q}app/api/v1.py
from fastapi import APIRouter router = APIRouter(prefix="/v1")@router.get("/ping")defping():return{"message":"pong"}requirements.txt
fastapi==0.99.1 uvicorn==0.23.2 gunicorn==20.1.0 五、使用 Gunicorn 管理 Uvicorn Workers
5.1 Gunicorn + Uvicorn 配置
创建启动脚本 gunicorn_conf.py:
import multiprocessing workers = multiprocessing.cpu_count()*2+1 worker_class ="uvicorn.workers.UvicornWorker" bind ="127.0.0.1:8000" timeout =30 keepalive =5# 日志 errorlog ="/opt/fastapi_app/logs/gunicorn.error.log" accesslog ="/opt/fastapi_app/logs/gunicorn.access.log" loglevel ="info"5.2 启动命令
mkdir -p logs gunicorn app.main:app -c gunicorn_conf.py 六、Nginx 反向代理配置
6.1 Nginx 配置文件
创建 /etc/nginx/sites-available/fastapi:
server { listen 80; server_name example.com; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_pass http://127.0.0.1:8000; } location /static/ { alias /opt/fastapi_app/app/static/; } } 启用配置:
sudoln -s /etc/nginx/sites-available/fastapi /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl restart nginx 七、生产环境 SSL/TLS
使用 Certbot 获取免费 Let’s Encrypt 证书:
sudoaptinstall -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com 自动续期检查:
sudo systemctl status certbot.timer 八、防火墙与安全
启用 UFW 并允许必要端口:
sudo ufw allow OpenSSH sudo ufw allow 'Nginx Full'sudo ufw enable九、日志、监控与性能指标
9.1 日志策略
# 日志目录 /opt/fastapi_app/logs/ # Nginx access log /var/log/nginx/access.log 可结合 logrotate 做定期清理:
sudonano /etc/logrotate.d/fastapi 内容示例:
/opt/fastapi_app/logs/*.log { daily rotate 14 compress missingok notifempty copytruncate } 9.2 监控指标
| 指标 | 采集方式 |
|---|---|
| CPU 利用率 | top / htop / vmstat |
| 内存使用 | free -m |
| 进程状态 | ps aux |
| 网络延迟 | MTR / traceroute |
| 99% 响应时间 | external 接口监控 |
十、压力测试与性能评测
使用 wrk 压测:
wrk -t4 -c500 -d60s http://example.com/health
| 并发连接数 | 平均响应时间(ms) | 吞吐 (req/s) |
|---|---|---|
| 100 | 18.5 | 5200 |
| 300 | 42.7 | 4800 |
| 500 | 96.3 | 3500 |
结果受网络环境、服务器硬件及应用逻辑影响,上表为参考数据。
十一、故障排查与常见问题
11.1 502 Bad Gateway
检查:
- Uvicorn/Gunicorn 是否运行
- Nginx 配置 proxy_pass 是否正确
- 端口是否被防火墙阻断
11.2 超时
Gunicorn timeout 可适当调大,或优化业务逻辑减少阻塞调用。
十二、后续优化建议
12.1 使用 Supervisor 管理进程
sudoaptinstall supervisor sudonano /etc/supervisor/conf.d/fastapi.conf 内容:
[program:fastapi] command=/opt/fastapi_app/venv/bin/gunicorn app.main:app -c /opt/fastapi_app/gunicorn_conf.py directory=/opt/fastapi_app autostart=true autorestart=true stderr_logfile=/opt/fastapi_app/logs/fastapi.err.log stdout_logfile=/opt/fastapi_app/logs/fastapi.out.log 重载:
sudo supervisorctl reread sudo supervisorctl update 12.2 HTTPS 强制 HSTS
在 Nginx SSL 配置中添加:
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; 结语
通过A5数据的教程,你已经完成了一个基于 Ubuntu 22.04 + FastAPI + Uvicorn + Nginx 的生产级 Python Web 服务部署,涵盖架构设计、配置细节、性能测试、日志监控等关键内容。接下来可根据业务规模,结合 Redis 缓存、PostgreSQL 数据库以及 CI/CD 自动化部署进一步提升系统稳定性与可维护性。
如需更深入的性能调优或结合 Kubernetes / Docker 部署方案,也可以在此基础上拓展讨论。