解决 Cloud Run 报错 Container failed to start and listen to PORT 端口监听失败修复
排查 Google Cloud Run 部署容器应用时报错 The user-provided container failed to start and listen on the port defined by the PORT environment variable (PORT=8080),分析 环境变量读取与绑定主机地址。
问题现象
使用 Google Cloud Run 部署容器化服务时,修订版本(Revision)部署失败并自动回滚:
Cloud Run error: The user-provided container failed to start and listen on the port defined by the PORT environment variable (PORT=8080).
Logs show: Server listening at http://127.0.0.1:3000
触发根因
- 容器内部应用将 HTTP 监听端口硬编码为
3000或其他端口,没有遵循 Cloud Run 动态注入的$PORT环境变量(默认 8080); - 应用监听在了本地环回地址
127.0.0.1/localhost上,导致容器外部网络探针无法穿越网络命名空间探测就绪状态; - 应用启动阶段执行同步数据库连接超时,未能在大约 4 分钟的启动超时窗口内完成端口监听。
解决步骤
在服务启动代码中动态读取环境变量 PORT 并绑定 0.0.0.0
以 Node.js / Express 为例:
const port = process.env.PORT || 8080;
app.listen(port, '0.0.0.0', () => {
console.log(`Server successfully listening on 0.0.0.0:${port}`);
});
以 Go 语言为例:
port := os.Getenv("PORT")
if port == "" { port = "8080" }
http.ListenAndServe(":" + port, nil)
确保应用将耗时的依赖初始化转为后台异步预热
保证进程启动 1 秒内立刻开放健康检测端口。
验证确认
重新构建并发布修订版本:
Cloud Run 就绪探测瞬间通过,绿色对勾亮起,修订版本顺利对外分发流量。


