Azure WebApp ZIP部署失败:$PORT被默认进程占用如何解决?
问题
使用以下GitHub Action脚本部署Streamlit应用到Azure Web App,代码能正常上传,但服务器无法连接$PORT,端口已被Azure默认服务占用。执行curl localhost:<$PORT>返回默认着陆页,说明Azure在自定义脚本启动前已启动默认服务。尝试设置WEBSITES_PORT但未传入容器,且因权限限制无法使用Dockerfile,只能通过ZIP包部署,求问题原因及解决办法。
GitHub Action脚本:
name: build and deploy Streamlit app on: push: branches: - main workflow_dispatch: jobs: build: runs-on: ubuntu-latest permissions: contents: read steps: - name: Checkout repo uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - name: Install pip run: | curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py python3 get-pip.py - name: Confirm pip installation run: | pip --version - name: Install dependencies run: | python3 -m pip install --upgrade pip pip install -r requirements.txt - name: Create ZIP package run: | zip -r streamlit-app.zip . -x "*.venv*" "*.vscode*" "*.git*" "__pycache__/*" - name: Upload ZIP artifact uses: actions/upload-artifact@v4 with: name: streamlit-app path: streamlit-app.zip deploy: runs-on: ubuntu-latest needs: build environment: name: 'Production' permissions: id-token: write contents: read steps: - name: Download ZIP artifact uses: actions/download-artifact@v4 with: name: streamlit-app - name: Unzip artifact run: unzip streamlit-app.zip - name: Make startup script executable run: chmod +x startup.sh - name: Deploy to Azure Web App id: deploy-to-webapp uses: azure/webapps-deploy@v3 with: app-name: 'streamlit-front' publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }} slot-name: 'Production' package: .
问题原因
- Azure Web Apps针对Python栈默认会自动启动基于WSGI的服务(如Flask/Django的开发服务器),这个进程会抢先占用
$PORT,导致后续启动的Streamlit无法绑定该端口。 WEBSITES_PORT未生效的原因是:通过ZIP包部署时,仅在本地或GitHub Action中设置该变量不会传递到容器环境,必须在Azure门户的应用程序设置中配置;另外,即使配置了变量,若启动脚本未正确读取并使用,也无法生效。
解决办法
1. 强制Streamlit使用Azure分配的端口
修改startup.sh,明确指定Streamlit绑定$PORT环境变量:
#!/bin/bash streamlit run your_app.py --server.port $PORT --server.address 0.0.0.0
注意替换your_app.py为实际的Streamlit入口文件名
2. 确保Azure识别并执行自定义启动脚本
- 在Azure门户的Web App配置页面,进入应用程序设置,添加
STARTUP_COMMAND变量,值为./startup.sh。 - 或者在GitHub Action的
azure/webapps-deploy步骤中,通过startup-command参数指定启动命令:
- name: Deploy to Azure Web App id: deploy-to-webapp uses: azure/webapps-deploy@v3 with: app-name: 'streamlit-front' publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }} slot-name: 'Production' package: . startup-command: './startup.sh'
3. 正确配置WEBSITES_PORT(可选)
若需要固定端口,在Azure门户的Web App应用程序设置中添加WEBSITES_PORT变量,值为你希望使用的端口号(如8501),同时确保启动脚本中Streamlit绑定该端口:
#!/bin/bash streamlit run your_app.py --server.port $WEBSITES_PORT --server.address 0.0.0.0
4. 禁用Azure默认的WSGI服务
在项目根目录创建requirements.txt时,若没有WSGI相关依赖(如Flask、Django),Azure不会自动启动默认服务;若必须包含这些依赖,可通过设置WSGI_APPLICATION变量为无效值来禁用默认启动,比如在应用程序设置中添加WSGI_APPLICATION=none:none。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

