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

Azure部署FastAPI应用遇问题:部署失败及启动配置无效求助

部署FastAPI+前端到Azure App Service问题解决

1. 解决GitHub Actions部署409冲突错误

  • 冲突多因部署时文件锁定或部署进程重复导致,在GitHub工作流的Azure/webapps-deploy@v2步骤中添加clean: true参数,强制清理旧文件后再部署:
    - name: Deploy to Azure Web App
      uses: Azure/webapps-deploy@v2
      with:
        app-name: <你的应用名>
        publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }}
        package: ./FastAPI
        clean: true
    
  • 同时确认没有其他部署任务在运行(比如Azure门户的手动部署),保证同一时间仅一个部署进程执行。

2. 解决Windows App Service无法使用startup-command的问题

Windows环境的Python App Service不支持startup-command参数,需通过以下两种方式配置启动逻辑:

方法一:生成web.config配置文件

在FastAPI目录下创建web.config文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified"/>
    </handlers>
    <httpPlatform processPath="%PYTHON_PATH%\python.exe"
                  arguments="-m uvicorn main:app --host 0.0.0.0 --port %HTTP_PLATFORM_PORT%"
                  stdoutLogEnabled="true"
                  stdoutLogFile="D:\home\LogFiles\python.log"
                  startupTimeLimit="60"
                  processesPerApplication="1">
      <environmentVariables>
        <environmentVariable name="PYTHONPATH" value="D:\home\site\wwwroot"/>
      </environmentVariables>
    </httpPlatform>
  </system.webServer>
</configuration>

该配置会让IIS通过httpPlatformHandler自动启动uvicorn,并使用Azure分配的端口。

方法二:修改应用设置

在Azure门户的应用设置中添加两个变量:

  • PYTHON_SCRIPT_PATH: 设置为main.py
  • PYTHON_WSGI_APPLICATION: 设置为main:app
    Azure会自动处理uvicorn的启动逻辑,无需手动指定命令。

3. 让前端文件可访问

有两种方案处理前端静态文件:

方案一:配置FastAPI托管静态文件

在main.py中添加静态文件服务配置,将前端目录挂载到路由:

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

# 挂载前端目录,访问根路径时自动返回index.html
app.mount("/", StaticFiles(directory="../Frontend", html=True), name="frontend")

# 示例API路由
@app.get("/api/hello")
async def hello():
    return {"message": "Hello World"}

部署时需确保Frontend目录被包含到部署包中,可修改GitHub工作流的package路径为项目根目录,或调整目录结构将Frontend移入FastAPI目录。

方案二:直接部署前端到wwwroot

修改GitHub工作流,合并Frontend和FastAPI的文件后再部署:

- name: Prepare deployment package
  run: |
    mkdir ./deploy
    cp -r ./FastAPI/* ./deploy/
    cp -r ./Frontend/* ./deploy/
- name: Deploy to Azure Web App
  uses: Azure/webapps-deploy@v2
  with:
    app-name: <你的应用名>
    publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }}
    package: ./deploy
    clean: true

4. 验证部署

  • 部署完成后访问App Service URL,确认前端页面或API接口正常返回内容。
  • 若仍有问题,可在Azure门户的「日志流」中查看Python日志,排查启动或运行错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 12:17:21