目录结构约定
/opt/your-app/
├── yourfile.py # FastAPI app 文件
├── yourfile.py # FastAPI app 文件
├── yourfile.py # FastAPI app 文件
├── yourfile.py # FastAPI app 文件
├── yourfile.py # FastAPI app 文件
├── .env # 可选,环境变量
├── requirements.txt
└── venv/- 创建虚拟环境并安装依赖
cd /opt/your-app
python3 -m venv venv
python3 -m venv venv
source venv/bin/activate
pip install fastapi uvicorn httpx(可选)
pip freeze > requirements.txt- 确认 FastAPI app 可被加载
yourfile.py 中必须存在:
from fastapi import FastAPI
app = FastAPI()- 手动启动测试
source /opt/your-app/venv/bin/activate
uvicorn yourfile:app --host 0.0.0.0 --port 8002测试:
curl http://127.0.0.1:8002/health
curl http://<VM_IP>:8002/health- 创建 systemd 用户(推荐)
sudo useradd --system --no-create-home --shell /usr/sbin/nologin youruser
sudo chown -R youruser:youruser /opt/your-app(如不需要独立用户可跳过)
- 创建 systemd service 文件
sudo nano /etc/systemd/system/your-app.service内容:
[Unit]
Description=Your FastAPI Service
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=youruser
Group=youruser
WorkingDirectory=/opt/your-app
EnvironmentFile=-/opt/your-app/.env
ExecStart=/opt/your-app/venv/bin/uvicorn yourfile:app --host 0.0.0.0 --port 8002
Restart=always
RestartSec=3
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target(如不用独立用户,改为 User=root / Group=root)
- 启动并设置开机自启
sudo systemctl daemon-reload
sudo systemctl enable your-app
sudo systemctl start your-app- 检查运行状态
systemctl status your-app --no-pager日志:
journalctl -u your-app -f- 确认端口监听
ss -lntp | grep 8002期望看到:
0.0.0.0:8002- 反向代理服务器/cloudflare tunnel指向目标
http://<VM_IP>:8002(健康检查路径可用 /health)
- 常用维护命令
sudo systemctl restart your-app
sudo systemctl stop your-app
sudo systemctl start your-app
sudo journalctl -u your-app -n 200 --no-pager完成标志
curl http://<VM_IP>:8002/health返回:
{"ok": true}systemd + FastAPI + 部署完成