1. 连接到你的服务器
使用 SSH 连接到服务器:
ssh root@<server-ip>
2. 获取登录凭据
系统已创建一个名为 fastapi 的专用用户来管理你的应用。
登录凭据保存在以下文件中: /root/.fastapi-creds
运行以下命令查看:
cat /root/.fastapi-creds
如需修改密码,请运行:
passwd fastapi
3. 切换到应用用户
切换到 fastapi 用户账户以管理你的应用:
su - flask
该账户包含你的 FastAPI 项目及其运行环境。
4. Project Structure
默认目录结构如下:
/home/fastapi/fastapi_app/
├── main.py → Your main FastAPI application file
├── venv/ → Virtual environment
└── __pycache__/ → Compiled Python files (auto-generated)
5. 管理你的应用
进入应用目录:
cd ~/fastapi_app
激活虚拟环境:
source venv/bin/activate
编辑主应用文件:
nano main.py
重启 FastAPI 服务以使更改生效:
sudo systemctl restart uvicorn-fastapi
6. Viewing Logs
可通过以下方式查看 Uvicorn 和 Nginx 的日志:
- Uvicorn logs:
/var/log/uvicorn/ - Nginx 错误日志:
/var/log/nginx/error.log - Nginx 访问日志:
/var/log/nginx/access.log
To view them:
sudo tail -f /var/log/uvicorn/*
7. 访问你的 API
服务启动后,可在浏览器中通过以下地址访问你的 FastAPI 应用: http://<server-ip>
Nginx 会自动将 HTTP 请求转发到运行 FastAPI 应用的 Uvicorn socket。
8. 修改域名或端口
如需更新服务器名称、端口或域名:
- 编辑 Nginx 站点配置:
sudo nano /etc/nginx/sites-available/uvicorn-fastapi - Test configuration:
sudo nginx -t - Reload Nginx:
sudo systemctl restart nginx
9. Uvicorn Service
FastAPI 应用通过名为 uvicorn-fastapi 的 systemd 服务运行。
It uses /home/fastapi/fastapi_app/main:app 作为应用入口,并在发生故障时自动重启。
管理服务:
systemctl status uvicorn-fastapi
systemctl restart uvicorn-fastapi
编辑服务配置:
sudo vim /etc/systemd/system/uvicorn-fastapi.service
sudo systemctl daemon-reload
sudo systemctl restart uvicorn-fastapi
sudo systemctl status uvicorn-fastapi
10. 启用 HTTPS(可选)
使用 Certbot 启用 HTTPS。