要将基于 **FastAPI** 的 AI 应用从本地开发环境升级为**生产级部署**,需要解决多个关键问题:性能、安全性、稳定性、可维护性和可扩展性。
下面我将详细介绍如何 **完善 FastAPI 的部署流程**,包括完整的配置代码和最佳实践。
---
## ✅ 目标
将你的 FastAPI 项目(如 AI 聊天后端)部署为一个:
- 高性能
- 安全可靠
- 可被公网访问
- 易于监控与维护
的生产服务。
---
## 🧩 完整部署架构图
```
[用户浏览器]
↓ HTTPS
[Nginx 反向代理 + SSL]
↓ (Gunicorn/Uvicorn)
[FastAPI 应用]
↓
[Ollama / 数据库 / 外部服务]
```
---
## 步骤 1:项目结构优化
```bash
ai-website/
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI 实例
│ ├── api/ # API 路由模块
│ │ └── chat.py
│ ├── config.py # 配置文件
│ └── utils/ # 工具函数(如调用 Ollama)
├── static/ # 前端静态文件
├── gunicorn.conf.py # Gunicorn 配置
├── nginx.conf # Nginx 配置模板
├── .env # 环境变量
├── Dockerfile # 容器化支持
└── requirements.txt
```
---
## 步骤 2:使用 `.env` 管理配置
### `.env`
```env
ENV=production
HOST=localhost
PORT=11434
MODEL_NAME=llama3
WORKERS=4
LOG_LEVEL=info
```
### `app/config.py`
```python
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
env: str = "development"
host: str = "localhost"
port: int = 11434
model_name: str = "llama3"
workers: int = 4
log_level: str = "info"
class Config:
env_file = ".env"
env_prefix = ""
settings = Settings()
```
> 安装依赖:
```bash
pip install python-dotenv pydantic-settings
```
---
## 步骤 3:主应用入口 (`app/main.py`)
```python
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import httpx
from app.config import settings
from app.api.chat import router as chat_router
app = FastAPI(title="Local AI Assistant API", version="1.0.0")
# 允许跨域(前端不同端口时需要)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 生产中应改为具体域名,如 ["https://yourdomain.com"]
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 包含路由
app.include_router(chat_router, prefix="/api")
@app.get("/")
def root():
return {"message": "AI Website Backend is running!"}
@app.on_event("startup")
async def startup_event():
print(f"Starting up in {settings.env} mode...")
# 可在此预加载资源或测试连接
```
---
## 步骤 4:定义 `/chat` 接口 (`app/api/chat.py`)
```python
from fastapi import APIRouter, Request
import httpx
router = APIRouter()
OLLAMA_URL = "http://localhost:11434/api/generate"
@router.post("/chat")
async def generate(request: Request):
data = await request.json()
prompt = data.get("prompt")
if not prompt:
raise HTTPException(status_code=400, detail="Missing prompt")
async with httpx.AsyncClient(timeout=30.0) as client:
try:
response = await client.post(
OLLAMA_URL,
json={
"model": "llama3",
"prompt": prompt,
"stream": False
}
)
response.raise_for_status()
result = response.json()
return {"response": result["response"]}
except httpx.RequestError as e:
raise HTTPException(status_code=503, detail=f"Model service unreachable: {str(e)}")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
```
---
## 步骤 5:使用 Gunicorn + Uvicorn 运行(多进程)
### 安装
```bash
pip install "uvicorn[standard]" gunicorn
```
### `gunicorn.conf.py`
```python
# 并发 worker 数量
workers = 4
# 异步工作模式
worker_class = "uvicorn.workers.UvicornWorker"
# 绑定地址
bind = "0.0.0.0:8000"
# 超时时间
timeout = 60
# 日志级别
loglevel = "info"
# 访问日志和错误日志
accesslog = "/var/log/gunicorn/access.log"
errorlog = "/var/log/gunicorn/error.log"
capture_output = True
# 进程名称
proc_name = "ai-website-api"
# 启动时清理旧文件描述符
reuse_port = True
```
### 启动命令
```bash
gunicorn -c gunicorn.conf.py app.main:app
```
> 💡 提示:你可以写成 shell 脚本 `start.sh` 自动运行。
---
## 步骤 6:Nginx 反向代理(推荐用于生产)
### `nginx.conf` 示例
```nginx
server {
listen 80;
server_name your-domain.com; # 或 localhost(内网)
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;
proxy_set_header X-Forwarded-Proto $scheme;
# WebSockets 支持(如果未来用到流式)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
# 如果你有前端静态文件
location /static/ {
alias /path/to/ai-website/static/;
expires 1h;
}
}
```
安装并启动 Nginx(Ubuntu 示例):
```bash
sudo apt update && sudo apt install nginx -y
sudo cp nginx.conf /etc/nginx/sites-available/default
sudo systemctl restart nginx
```
---
## 步骤 7:添加 HTTPS(Let's Encrypt)
```bash
# 安装 Certbot
sudo apt install certbot python3-certbot-nginx -y
# 获取证书(替换为你的真实域名)
sudo certbot --nginx -d your-domain.com
```
之后 Nginx 会自动配置 HTTPS 并重定向 HTTP → HTTPS。
---
## 步骤 8:使用 Systemd 管理服务(开机自启)
### 创建 systemd 服务文件
```bash
sudo nano /etc/systemd/system/ai-website.service
```
内容如下:
```ini
[Unit]
Description=AI Website FastAPI Service
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/path/to/ai-website
ExecStart=/usr/local/bin/gunicorn -c gunicorn.conf.py app.main:app
Restart=always
EnvironmentFile=/path/to/ai-website/.env
[Install]
WantedBy=multi-user.target
```
启用并启动:
```bash
sudo systemctl daemon-reexec
sudo systemctl enable ai-website
sudo systemctl start ai-website
```
查看状态:
```bash
sudo systemctl status ai-website
```
---
## 步骤 9:容器化部署(Docker)
### `Dockerfile`
```dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["gunicorn", "-c", "gunicorn.conf.py", "app.main:app"]
```
### 构建镜像
```bash
docker build -t ai-website .
```
### 运行容器
```bash
docker run -d \
--name ai-website \
-p 8000:8000 \
--add-host=host.docker.internal:host-gateway \ # 让容器访问宿主机上的 Ollama
ai-website
```
> 注意:如果你的 Ollama 在宿主机上运行,需通过 `host.docker.internal` 访问。
---
## 步骤 10:日志监控与健康检查
### 添加健康检查接口
```python
@app.get("/health")
def health_check():
return {"status": "healthy", "env": settings.env}
```
然后可以用 Prometheus + Grafana 或简单脚本定时检测。
---
## ✅ 总结:完善的 FastAPI 部署清单
| 功能 | 是否完成 | 工具 |
|------|----------|------|
| 多进程并发 | ✅ | Gunicorn + Uvicorn |
| 环境变量管理 | ✅ | Pydantic Settings + `.env` |
| 请求路由分离 | ✅ | APIRouter 模块化 |
| 跨域支持 | ✅ | CORSMiddleware |
| 反向代理 | ✅ | Nginx |
| HTTPS 加密 | ✅ | Let's Encrypt |
| 开机自启 | ✅ | systemd |
| 日志记录 | ✅ | Gunicorn + Nginx 日志 |
| 容器化支持 | ✅ | Docker |
| 错误处理 | ✅ | HTTPException 统一捕获 |
---
## 🛡️ 安全建议(生产必备)
1. **禁止 `allow_origins=["*"]`** → 改为具体前端域名
2. **添加速率限制** → 使用 `slowapi` 或 Nginx 限流
3. **输入校验** → 使用 Pydantic 模型验证
4. **不要暴露敏感路径** → 如 `/docs` 在生产中可关闭
5. **定期更新依赖** → `pip list --outdated`
---