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

如何在Azure App Service Docker容器中配置Nginx支持wss

解决方案

你不需要在容器内部配置SSL证书,Azure App Service 会在平台边缘负载层统一终止TLS连接,再将明文请求转发到你的容器,WebSocket连接失败是反向代理配置缺失、平台开关未开启共同导致的,按以下步骤调整即可:

1. 修改Nginx配置

替换原有nginx.conf内容,补全必需的请求头透传规则、WebSocket超时配置:

map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

server {
    listen 8502 default_server;

    # 通用代理头配置
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;

    # Flask接口转发
    location /api/run {
        proxy_pass http://localhost:5000/run;
    }

    location /api/results {
        proxy_pass http://localhost:5000/results;
    }

    # Streamlit 前端与WebSocket转发
    location / {
        proxy_pass http://localhost:8501;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_buffering off;
        # 配置长连接超时,避免空闲WebSocket被主动断开
        proxy_read_timeout 86400;
    }
}

配置说明:原配置仅添加了Upgrade/Connection头,未透传Azure转发时携带的原始Host、X-Forwarded-Proto头,会导致后端服务收到的请求源信息错误,无法匹配HTTPS/WSS的访问上下文,直接拒绝WebSocket握手。

2. 调整Streamlit配置

Streamlit默认会校验请求来源,反向代理场景下需要关闭跨域校验、信任代理头,二选一配置即可:

  • 方案A:直接修改启动命令,替换Dockerfile中Streamlit启动部分为:
poetry run streamlit run ./dashboard/dashboard.py --server.address 127.0.0.1 --server.port 8501 --server.enableCORS false --server.enableXsrfProtection false --server.trustProxyHeaders true
  • 方案B:在代码目录下创建.streamlit/config.toml并写入以下配置,随镜像一起构建:
[server]
address = "127.0.0.1"
port = 8501
enableCORS = false
enableXsrfProtection = false
trustProxyHeaders = true

3. 检查Azure App Service侧配置

  • 进入App Service「配置-常规设置」页,将Web套接字开关设为开启,该选项默认关闭,未开启时平台会直接拦截WebSocket连接请求。
  • 在应用配置中添加环境变量WEBSITES_PORT=8502,明确告知平台你的容器监听端口为8502,避免端口探测失败。

配置完成后重新构建镜像部署即可,不需要在容器内配置任何SSL证书,平台侧的SSL卸载逻辑会自动处理wss到ws的协议转换。


内容的提问来源于stack exchange,提问作者Justin D. Harris

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 00:57:31