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

部署Streamlit至GCP Cloud Run遇/healthz路径错误的解决方法

解决Streamlit部署到Cloud Run的/healthz未找到错误

Cloud Run默认会向/healthz路径发送健康检查请求,但Streamlit本身并未提供这个端点,因此会返回404错误。以下是几种可行的解决办法:

方法1:修改Cloud Run的健康检查路径(推荐)

Streamlit内置了一个健康检查端点/_stcore/health,你可以直接将Cloud Run的健康检查路径替换为这个地址,无需修改代码:

  • 控制台操作:
    1. 打开Cloud Run控制台,找到你的服务
    2. 点击「编辑&部署新版本」
    3. 展开「容器」部分的「健康检查」配置
    4. 将「存活检查」和「就绪检查」的路径都改为/_stcore/health
    5. 保存并重新部署服务
  • 命令行操作:
    gcloud run services update YOUR_SERVICE_NAME \
      --set-health-checks=liveness=http-get:///_stcore/health,readiness=http-get:///_stcore/health \
      --region YOUR_REGION
    

方法2:在Streamlit应用中添加/healthz端点

如果不想修改Cloud Run配置,可以通过Streamlit底层的FastAPI扩展添加/healthz路由:

import streamlit as st
from fastapi import FastAPI

# 创建FastAPI实例
health_app = FastAPI()

# 定义/healthz端点
@health_app.get("/healthz")
async def health_check():
    return {"status": "healthy"}

# 将FastAPI应用挂载到Streamlit的服务器上
st._server.server.Server.add_app(health_app)

# 你的Streamlit应用代码
st.title("My Streamlit App")
# ... 其他业务代码

注意:该方法依赖Streamlit的内部API,不同版本可能存在兼容性问题,建议优先使用方法1。

方法3:使用反向代理(适合复杂场景)

如果需要额外的路由配置,可以在Docker容器中添加Nginx作为反向代理,将/healthz请求转发到Streamlit的内置健康端点:

  1. 在项目根目录创建nginx.conf文件:
server {
    listen 8080;
    location / {
        proxy_pass http://localhost:8501;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
    location /healthz {
        proxy_pass http://localhost:8501/_stcore/health;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
  1. 修改Dockerfile,安装Nginx并启动:
FROM python:3.10-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .
COPY nginx.conf /etc/nginx/conf.d/default.conf

RUN apt-get update && apt-get install -y nginx && rm -rf /var/lib/apt/lists/*

# 启动Nginx和Streamlit
CMD ["sh", "-c", "nginx && streamlit run app.py --server.port=8501 --server.address=0.0.0.0"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:05:20