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

Cloud Run部署报错:容器无法启动并监听PORT环境变量指定端口

问题根因

Cloud Run对运行的容器有强制要求:容器必须持续运行一个HTTP服务,监听配置指定的端口(你当前配置的是8080),平台会定期发起健康检查确认服务可用。你当前的hello.py仅执行一次打印逻辑后就直接退出,没有启动任何web服务监听端口,因此触发了健康检查失败报错。

修复步骤
  • 第一步:调整代码,添加端口监听逻辑
    你可以直接使用Python内置的http.server模块实现轻量web服务,无需安装额外依赖,修改后的hello.py代码如下:
import os
from http.server import HTTPServer, BaseHTTPRequestHandler

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.end_headers()
        self.wfile.write(b'Hello World')

if __name__ == "__main__":
    # 优先读取Cloud Run注入的PORT环境变量,默认 fallback 到8080
    port = int(os.environ.get("PORT", 8080))
    # 必须监听0.0.0.0,不能用127.0.0.1,否则容器外部无法访问
    server = HTTPServer(('0.0.0.0', port), RequestHandler)
    server.serve_forever()

注意:监听地址必须配置为0.0.0.0,如果写成本地回环地址127.0.0.1会导致Cloud Run的健康检查请求无法到达服务,仍然会触发相同报错。

  • 可选扩展方案:使用Flask框架实现服务
    如果后续需要扩展服务功能,可以用Flask框架实现,首先新增requirements.txt文件:
flask==2.3.3

修改Dockerfile添加依赖安装步骤:

FROM python:3.9.7-slim-buster

WORKDIR /app

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

COPY . .

CMD [ "python3", "hello.py" ]

对应的hello.py代码:

import os
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello World"

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 8080))
    app.run(host='0.0.0.0', port=port)
  • 第二步:验证Docker镜像本地运行正常
    重新构建镜像后本地运行测试,执行命令:
docker run -p 8080:8080 <你的镜像名>

访问localhost:8080能正常返回Hello World说明镜像配置正确。

  • 第三步:重新部署到Cloud Run
    你当前的cloudbuild.yaml配置无需额外修改,重新推送镜像执行部署即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:30:02