在Azure Web App部署FastAPI遇504网关超时问题求助
Azure Web App部署FastAPI出现504 GatewayTimeout的排查思路
我正尝试在Azure Web App中运行FastAPI应用,但出现了以下错误:
azure 504.0 GatewayTimeout
以下是结合你提供的配置、代码和截图整理的可能原因及排查方向:
一、启动命令配置错误
FastAPI在Azure Web App上运行需要明确指定兼容的启动参数:
- 你代码中的启动逻辑使用了
uvicorn.run('main:app', reload=True),但reload是开发模式,不适合生产环境,且未指定host和port。Azure Web App要求应用绑定0.0.0.0,并使用环境变量PORT指定的端口(默认8000)。 - 检查Azure Web App的配置>常规设置>启动命令,建议设置为:
uvicorn main:app --host 0.0.0.0 --port $PORT
二、依赖部署不完整
从GitHub Actions流程来看:
- 构建阶段虽安装了依赖,但打包时排除了虚拟环境
venv,而部署步骤未重新安装依赖。Azure Web App不会自动识别并安装依赖,除非使用Oryx自动构建机制。 - 优化方案:
- 在部署步骤添加依赖安装命令:
pip install -r requirements.txt - 改用Azure官方的Oryx构建(推荐),它会自动检测Python项目并处理依赖安装
- 在部署步骤添加依赖安装命令:
三、应用初始化超时
代码中lifespan异步上下文管理器在启动时调用await azure_auth.load_openid_config(),如果这个请求因网络限制、Azure AD端点不可达或配置错误卡住,会导致应用无法正常启动,触发网关超时:
- 临时注释
lifespan相关代码,测试应用是否能正常启动,排除初始化步骤的问题 - 检查Azure Web App的出站网络是否允许访问
login.microsoftonline.com等Azure AD相关域名 - 验证
AzureAuth类中load_openid_config的实现逻辑是否正确
四、资源不足
如果使用的是Azure Web App免费层或基础层,可能因CPU、内存配额不足导致应用启动缓慢或失败:
- 临时升级到S1及以上定价层测试,确认是否是资源限制问题
五、日志定位问题
直接查看Azure Web App的日志流是最有效的排查方式:
- 登录Azure门户,进入Web App的监控>日志流,查看应用启动时的错误日志,比如依赖缺失、代码异常、启动命令错误等信息
附:用户提供的配置信息
GitHub Actions构建部署工作流
name: Build and deploy Python app to Azure Web App - segato-fast-api on: push: branches: - dev workflow_dispatch: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Python version uses: actions/setup-python@v5 with: python-version: '3.12' - name: Create and start virtual environment run: | python -m venv venv source venv/bin/activate - name: Install dependencies run: pip install -r requirements.txt # Optional: Add step to run tests here (PyTest, Django test suites, etc.) - name: Zip artifact for deployment run: zip release.zip ./* -r - name: Upload artifact for deployment jobs uses: actions/upload-artifact@v4 with: name: python-app path: | release.zip !venv/ deploy: runs-on: ubuntu-latest needs: build environment: name: 'Production' url: ${{ steps.deploy-to-webapp.outputs.webapp-url }} permissions: id-token: write #This is required for requesting the JWT steps: - name: Download artifact from build job uses: actions/download-artifact@v4 with: name: python-app - name: Unzip artifact for deployment run: unzip release.zip - name: Login to Azure uses: azure/login@v2 with: client-id: ${{ secrets.xx}} tenant-id: ${{ secrets.xx}} subscription-id: ${{ secrets.xx}} - name: 'Deploy to Azure Web App' uses: azure/webapps-deploy@v3 id: deploy-to-webapp with: app-name: 'segato-fast-api' slot-name: 'Production'
FastAPI代码
from fastapi import FastAPI,Request from fastapi.middleware.cors import CORSMiddleware from fastapi_azure_auth import SingleTenantAzureAuthorizationCodeBearer import uvicorn from fastapi import FastAPI, Security from settings import Settings from contextlib import asynccontextmanager from typing import AsyncGenerator from enums import settings from routers.router1 import router1_router from routers.docs import tags_metadata from utils.azure.azure_auth import AzureAuth from utils.azure.azure_logging import azure_logger azure_auth = AzureAuth() @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: await azure_auth.load_openid_config() yield app = FastAPI( openapi_tags=tags_metadata, swagger_ui_oauth2_redirect_url='/oauth2-redirect', swagger_ui_init_oauth={ 'usePkceWithAuthorizationCodeGrant': True, 'clientId': settings.xx, 'scopes': settings.xx, }, ) app.include_router(router1_router) if settings.BACKEND_CORS_ORIGINS: app.add_middleware( CORSMiddleware, allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS], allow_credentials=True, allow_methods=['*'], allow_headers=['*'], ) if __name__ == '__main__': uvicorn.run('main:app', reload=True)
Azure配置截图

内容的提问来源于stack exchange,提问作者Thomas Segato
相关产品推荐
相关产品推荐

