You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将FastAPI API部署到DigitalOcean Droplet上?

FastAPI 部署到DigitalOcean Ubuntu Droplet 操作指引

1. 前置准备

  • 本地开发完成的FastAPI项目,已导出依赖到requirements.txt文件
  • Droplet的SSH登录权限及公网IP
  • 本地具备SSH连接工具

2. 服务器基础环境配置

首先通过SSH登录服务器:

ssh root@你的Droplet公网IP

执行系统包更新:

apt update && apt upgrade -y

安装所需基础软件:

apt install python3-pip python3-venv nginx -y

3. 上传项目到服务器

两种常用方式二选一即可:

  • 本地执行SCP命令上传:scp -r 本地FastAPI项目文件夹路径 root@你的Droplet公网IP:/opt/
  • 服务器安装git后直接拉取项目仓库到/opt目录

4. 项目运行环境配置

进入服务器上的项目目录:

cd /opt/你的项目文件夹名

创建并激活虚拟环境:

python3 -m venv venv
source venv/bin/activate

安装项目依赖及运行工具:

pip install -r requirements.txt
pip install uvicorn gunicorn

测试服务是否可正常启动:

uvicorn main:app --host 0.0.0.0 --port 8000

本地访问http://Droplet公网IP:8000/docs可打开FastAPI接口文档即代表配置正常,按Ctrl+C停止测试服务。

5. 配置进程守护

创建systemd服务文件实现服务开机自启、异常自动重启:

nano /etc/systemd/system/fastapi.service

写入以下配置:

[Unit]
Description=FastAPI Service
After=network.target

[Service]
User=root
WorkingDirectory=/opt/你的项目文件夹名
ExecStart=/opt/你的项目文件夹名/venv/bin/gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 127.0.0.1:8000
Restart=always

[Install]
WantedBy=multi-user.target

保存退出后执行以下命令启动服务:

systemctl daemon-reload
systemctl start fastapi
systemctl enable fastapi

执行systemctl status fastapi显示active(running)即代表服务启动成功。

6. 配置Nginx反向代理

创建Nginx站点配置文件:

nano /etc/nginx/sites-available/fastapi

写入以下配置:

server {
    listen 80;
    server_name 你的Droplet公网IP 绑定的域名(可选);

    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;
    }
}

启用配置并重载Nginx:

ln -s /etc/nginx/sites-available/fastapi /etc/nginx/sites-enabled/
nginx -t
systemctl reload nginx

7. 防火墙配置

执行以下命令放行HTTP/HTTPS端口:

ufw allow 'Nginx Full'
ufw enable

配置完成后直接访问http://Droplet公网IP即可调用API,访问http://Droplet公网IP/docs可查看接口文档。

内容的提问来源于stack exchange,提问作者Niusoski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:45:00