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

Azure部署Flask API遇503错误:容器启动及虚拟环境问题求助

问题:Azure Linux托管Web App部署Flask API启动失败及虚拟环境异常

1. Flask API代码(app.py)

app = Flask(__name__)
CORS(app)
basedir = os.path.abspath(os.path.dirname(__file__))
from db_helpers import init_db

app.config[
    'SQLALCHEMY_DATABASE_URI'
] = my_microsoft_azure_database_connection.database_connection_uri
app.config['DEBUG'] = False
app.config['TESTING'] = False
app.config['CSRF_ENABLED'] = True
app.config['SECRET_KEY'] = 'needs-to-be-changed'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db_engine = init_db()
db = SQLAlchemy(app, metadata=BaseDeclarative.metadata)

api = Api(app, default_mediatype='application/json')

api.add_resource(
    ListAssessmentCaseEndpoint, '/assessments', endpoint='list_assessment_cases'
)
api.add_resource(
    AssessmentCaseEndpoint, '/assessments/<uuid:uuid>', endpoint='assessment_cases'
)

api.add_resource(ListAuditLogEndpoint, '/auditing', endpoint='list_audit_logs')
api.add_resource(AuditLogEndpoint, '/auditing/<uuid:uuid>', endpoint='audit_logs')

api.add_resource(HealthCheckEndpoint, '/healthcheck', endpoint='health_check')


# Add Swagger documentation to Flask app
Swagger(app, template_file='swagger.yml')

2. 构建工件的ARM模板

trigger:
- develop

variables:

  webAppName: 'test-api'

  environmentName: 'test-api'

  projectRoot: $(System.DefaultWorkingDirectory)/WebApi

  pythonVersion: '3.7'

stages:
- stage: Build
  displayName: Build stage
  jobs:
  - job: BuildJob
    steps:
    - task: UsePythonVersion@0
      inputs:
        versionSpec: '$(pythonVersion)'
      displayName: 'Use Python $(pythonVersion)'
    
    - script: |
        python3 -m venv .venv
        source .venv/bin/activate
        pip install --upgrade pip
        pip install waitress==2.1.2
        pip install setup
        pip install -r requirements.txt
      workingDirectory: $(projectRoot)
      displayName: "Install requirements"

    - task: ArchiveFiles@2
      displayName: 'Archive files'
      inputs:
        rootFolderOrFile: '$(projectRoot)'
        includeRootFolder: false
        archiveType: zip
        archiveFile: $(Build.ArtifactStagingDirectory)/$(webAppName).zip
        replaceExistingArchive: true

    - publish: $(Build.ArtifactStagingDirectory)/$(webAppName).zip
      displayName: 'Upload package'
      artifact: drop

3. 部署到Linux Web App的模板

steps:
- task: AzureWebApp@1
  displayName: 'Azure Web App Deploy: test-api'
  inputs:
    azureSubscription: 'azurerm-sp-apps-dev'
    appType: webAppLinux
    appName: 'testt-api'
    package: '$(System.DefaultWorkingDirectory)/test-api-WebApi/drop/test-api.zip'
    runtimeStack: 'PYTHON|3.7'
    startUpCommand: 'python3.7 -m pip install -r requirements.txt && python3.7 -m pip install gunicorn && python3.7 -m gunicorn --bind=0.0.0.0:80 --workers=4 app:app'
    configurationStrings: '-StartupCommand startup.sh'
    deploymentMethod: zipDeploy

4. 应用网关配置模板

steps:
- task: test-AppGateway.appGatewayCreate-task.test-AppGateway-CreateUpdate@1
  displayName: 'Create or Update Application Gateway Config API'
  inputs:
    connectedServiceName: 'azurerm-sp-apps-dev'
    AppName: 'test-api'
    HealthProbeUri: /healthcheck
  timeoutInMinutes: 120
  retryCountOnTaskFailure: 10

5. 异常现象

  • 应用日志显示gunicorn已正常启动,监听http://0.0.0.0:80,4个worker已启动;
  • 平台日志报错:

    Platform logs contain errors or warnings
    Container test-api_0_a8607b6c for site test-api did not start within expected time limit.
    Container test-api_0_a8607b6c didn't respond to HTTP pings on port: 8000, failing site start

  • /healthcheck端点无响应,返回503 Server Unavailable,应用网关返回502 Bad Gateway;
  • 构建阶段创建的虚拟环境在部署阶段无法识别:
    • 激活时报错:/opt/startup/startup.sh: startup.sh: not found name source not found;
    • 部署使用的Python版本与虚拟环境定义的不一致;
  • 部署时实际执行的Docker命令:
docker run -d -p 9286:8000 --expose=49494 --name test-api_0_f5ccb0ab -e WEBSITE_CORS_ALLOWED_ORIGINS=https://test.dev.app.test.com,https://test.eastus2-dev-platform-ase1.appserviceenvironment.net -e WEBSITE_CORS_SUPPORT_CREDENTIALS=True -e WEBSITES_PORT=80 -e WEBSITE_SITE_NAME=test-api -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=test-api.eastus2-dev-platform-ase1.appserviceenvironment.net -e WEBSITE_INSTANCE_ID=MY-ID -e HTTP_LOGGING_ENABLED=1 -e WEBSITE_USE_DIAGNOSTIC_SERVER=True appsvc/python:3.7_20221128.12.tuxprod python3.7 -m pip install -r requirements.txt && python3.7 -m pip install gunicorn && python3.7 -m gunicorn --bind=0.0.0.0:80 --workers=4 app:app

6. 已尝试但无效的方法

  • 调高WEBSITES_CONTAINER_START_TIME_LIMIT至1800;
  • 修改WEBSITES_PORT为8000或80;
  • 更换启动命令(waitress-serve、gunicorn、flask);
  • 修改Flask服务端口(80、5000、8000、8081);

7. 请求解决

请问该如何解决这些问题?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 10:55:20