无法将FastAPI部署至Heroku的问题求助
问题:Heroku部署FastAPI应用出现H14错误
已尝试操作
- 多次修改Procfile配置
- 反复检查依赖安装状态
- 再三核对文件路径与命名
- 测试过两种Procfile配置均失败:
web: uvicorn main:app --workers 4web gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:server
main.py代码
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from videoGames import vgRouter # 定义服务实例 server = FastAPI() origins = ['*'] server.add_middleware( CORSMiddleware, allow_origins = origins, allow_credentials = True, allow_methods = ['*'], allow_headers = ['*'], ) @server.get('/') def welcomeUser(): return {"message": "Welcome to my API!"} # 注册游戏路由 server.include_router(vgRouter.router)
Heroku日志
2022-10-05T03:08:40.691697+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=land-of-gamingapi.herokuapp.com request_id=b6f472d3-a557-4bbd-9419-53d1542139be fwd="23.84.247.49" dyno= connect= service= status=503 bytes= protocol=https 2022-10-05T03:08:40.830495+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=land-of-gamingapi.herokuapp.com request_id=902be7d5-9ee5-400e-bb25-1958b11abdc4 fwd="23.84.247.49" dyno= connect= service= status=503 bytes= protocol=https 2022-10-05T03:08:41.413337+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=land-of-gamingapi.herokuapp.com request_id=c94caef3-e237-4da0-93e8-42f4330dfde1 fwd="23.84.247.49" dyno= connect= service= status=503 bytes= protocol=https 2022-10-05T03:08:41.641962+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=land-of-gamingapi.herokuapp.com request_id=95be4fd7-bc74-4541-bb54-4f737b02be19 fwd="23.84.247.49" dyno= connect= service= status=503 bytes= protocol=https
解决方案
1. 修复代码缩进错误
代码中server.include_router(vgRouter.router)被错误缩进在welcomeUser函数内部,函数执行到return语句后会直接终止,导致路由永远无法注册。需将其移到函数外部:
@server.get('/') def welcomeUser(): return {"message": "Welcome to my API!"} # 移至函数外部,确保路由正常注册 server.include_router(vgRouter.router)
2. 修正Procfile配置
你的FastAPI实例名为server而非app,且Heroku要求应用绑定到0.0.0.0并使用环境变量提供的端口,以下是两种正确配置:
方案一:使用uvicorn
web: uvicorn main:server --host 0.0.0.0 --port $PORT --workers 4
方案二:使用gunicorn+uvicorn worker
web: gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:server --bind 0.0.0.0:$PORT
3. 启动web进程
部署后执行以下命令,确保至少有一个web dyno在运行,这是解决H14错误的核心:
heroku ps:scale web=1
4. 检查依赖文件
确保requirements.txt包含所有必要依赖:
fastapi uvicorn gunicorn # 需添加videoGames模块依赖的其他包
内容的提问来源于stack exchange,提问作者Keyshawn Jones
相关产品推荐
相关产品推荐

