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

AWS EC2实例部署的FastAPI代码更新后仍运行旧版本求助

解决FastAPI更新后依旧运行旧代码的问题

以下是排查和解决的具体步骤:

1. 确认代码目录与服务指向是否匹配

  • 找出当前运行的FastAPI进程路径:
    ps aux | grep uvicorn  # 用gunicorn的话替换为gunicorn
    
    查看输出中的进程命令,确认其工作目录是否为你新克隆的仓库路径。如果指向旧目录,说明服务未关联新代码。

2. 重启FastAPI服务

使用systemd管理服务的场景

  • 编辑服务配置文件(例如/etc/systemd/system/fastapi.service),将WorkingDirectory改为新克隆的仓库路径,确保ExecStart命令指向新目录的代码:
    [Unit]
    Description=FastAPI Service
    After=network.target
    
    [Service]
    User=ubuntu
    WorkingDirectory=/home/ubuntu/new-fastapi-repo  # 替换为新路径
    ExecStart=/home/ubuntu/venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000
    Restart=always
    
    [Install]
    WantedBy=multi-user.target
    
  • 重新加载配置并重启服务:
    sudo systemctl daemon-reload
    sudo systemctl restart fastapi
    

直接后台运行的场景

  • 终止旧进程:
    pkill uvicorn  # 或使用kill <PID>,PID从ps aux结果中获取
    
  • 进入新克隆的仓库目录,激活虚拟环境(若使用)后重启服务:
    cd /home/ubuntu/new-fastapi-repo
    source venv/bin/activate
    uvicorn main:app --host 0.0.0.0 --port 8000 &
    

3. 清理缓存

  • 清理Python字节码缓存:
    cd /home/ubuntu/new-fastapi-repo
    rm -rf __pycache__
    find . -name "*.pyc" -delete
    
  • 清理Nginx缓存(若开启了反向代理或静态缓存):
    找到Nginx配置中的缓存路径(例如proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;),删除缓存文件并重启Nginx:
    sudo rm -rf /var/cache/nginx/*
    sudo systemctl restart nginx
    

4. 确认代码为最新版本

  • 进入新克隆的仓库目录,拉取最新代码:
    cd /home/ubuntu/new-fastapi-repo
    git pull origin main  # 替换为你的分支名称
    

5. 检查Nginx反向代理配置

  • 打开Nginx配置文件(例如/etc/nginx/sites-available/fastapi),确认proxy_pass指向当前运行的FastAPI服务地址(例如http://127.0.0.1:8000),若服务端口或地址有变动,修改后重启Nginx:
    sudo systemctl restart nginx
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:55:22