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

Google云VM中FastAPI关闭SSH终端后停止服务的求助

问题原因

你直接在SSH终端启动的FastAPI进程属于当前终端会话,当SSH断开(关闭终端)后,会话会向进程发送终止信号,导致服务在一段时间后停止,Nginx无法找到后端服务就会返回502错误。

解决方法

1. 临时方案:用nohup让进程脱离终端运行

在启动FastAPI的命令前加上nohup,并将输出重定向到日志文件,确保进程不受终端关闭影响:

nohup uvicorn main:app --host 127.0.0.1 --port 8000 > fastapi-service.log 2>&1 &
  • nohup:让进程忽略终端断开的终止信号
  • > fastapi-service.log 2>&1:把服务的输出和错误信息都写入日志文件,方便后续排查问题
  • 最后的&:让进程在后台运行

2. 长期稳定方案:用systemd管理服务(推荐)

如果需要服务长期稳定运行,且能自动重启,建议用systemd做系统服务管理:

  1. 创建服务配置文件:
sudo nano /etc/systemd/system/fastapi-ml.service
  1. 写入以下内容(替换成你的实际信息):
[Unit]
Description=FastAPI ML Model Service
After=network.target

[Service]
User=你的VM用户名  # 比如ubuntu
WorkingDirectory=/你的项目所在路径  # 比如/home/ubuntu/ml-project
ExecStart=/usr/bin/uvicorn main:app --host 127.0.0.1 --port 8000
Restart=always  # 进程意外退出时自动重启

[Install]
WantedBy=multi-user.target
  1. 重载systemd配置并启动服务:
sudo systemctl daemon-reload
sudo systemctl start fastapi-ml
sudo systemctl enable fastapi-ml  # 设置开机自启
  1. 查看服务状态确认正常运行:
sudo systemctl status fastapi-ml

3. 修复Nginx配置的小错误

你的Nginx配置里server_name后面多了个冒号,修正后重启Nginx:

server {
    listen 80;
    server_name 你的公网IP;  # 去掉冒号,直接填写IP
    location / {
        proxy_pass http://127.0.0.1:8000;
        # 可添加以下代理优化配置,避免连接超时问题
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_connect_timeout 300s;
        proxy_send_timeout 300s;
        proxy_read_timeout 300s;
    }
}

重启Nginx:

sudo systemctl restart nginx

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:05:21