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

部署在AWS EC2的FastAPI应用关闭终端后如何持续运行?

解决FastAPI在AWS EC2部署的两个问题:后台持久运行与Nginx配置优化

一、让FastAPI应用后台持久运行(关闭终端不中断)

用systemd创建守护进程是Linux环境下稳定管理后台服务的标准方式,步骤如下:

  1. 创建systemd服务文件:
    编辑 /etc/systemd/system/fastapi.service,填入以下内容(替换注释中的自定义信息):
    [Unit]
    Description=FastAPI Application
    After=network.target
    
    [Service]
    User=ubuntu  # 替换为你的EC2实例用户名,如ec2-user
    WorkingDirectory=/home/ubuntu/your-fastapi-project  # 替换为你的FastAPI项目根目录
    ExecStart=/usr/bin/python3 -m uvicorn main:app --host 127.0.0.1 --port 8000
    Restart=always
    
    [Install]
    WantedBy=multi-user.target
    
  2. 加载配置并启动服务:
    sudo systemctl daemon-reload
    sudo systemctl start fastapi
    sudo systemctl enable fastapi  # 设置开机自动启动
    
  3. 验证服务运行状态:
    sudo systemctl status fastapi
    

二、修复Nginx配置问题

你的现有配置缺少必要的代理头部参数,且server_name配置不规范,修改后的完整配置如下:

server {
    listen 80;
    server_name 你的EC2公网IP;  # 替换为实际的EC2公网IP,例如192.168.1.100

    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使配置生效:

sudo systemctl restart nginx

额外检查项

  • 确认EC2安全组已开放80端口(HTTP)的入站规则,允许目标访问IP段(如0.0.0.0/0或指定IP)
  • 若实例启用了防火墙(如ufw),需允许80端口:sudo ufw allow 80

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:20:28