遵循Google Cloud Run指南部署Node.js服务时端口启动报错
按照Google Cloud Run从源码部署Node.js服务的指南操作,执行gcloud run deploy时出现错误:
Deployment failed ERROR: (gcloud.run.deploy) Revision 'mybackend-00001-ctc' is not ready and cannot serve traffic. The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable. Logs for this revision might contain more information.
使用的index.js代码:
import express from 'express'; const app = express(); app.get('/', (req, res) => { const name = process.env.NAME || 'World'; res.send(`Hello ${name}!`); }); const port = parseInt(process.env.PORT) || 8080; app.listen(port, () => { console.log(`helloworld: listening on port ${port}`); });
package.json配置:
{ "name": "helloworld", "description": "Simple hello world sample in Node", "version": "1.0.0", "private": true, "main": "index.js", "scripts": { "start": "node index.js" }, "engines": { "node": ">=16.0.0" }, "author": "Google LLC", "license": "Apache-2.0", "dependencies": { "express": "^4.17.1" } }
1. 启用ES模块支持
代码使用了import ES模块语法,但Node.js默认将.js文件识别为CommonJS模块,导致启动失败。需在package.json中添加"type": "module"字段:
{ // 保留原有配置 "type": "module", // 保留原有配置 }
2. 明确监听所有网络接口
Cloud Run要求容器必须监听0.0.0.0(所有网络接口),而非仅本地回环地址。修改app.listen调用,指定监听地址:
app.listen(port, '0.0.0.0', () => { console.log(`helloworld: listening on port ${port}`); });
3. 排查依赖安装问题
部署过程中可能存在依赖未正确安装的情况,执行以下命令查看最新构建日志:
gcloud builds logs list --latest
如果发现依赖安装失败,先在本地执行npm install验证依赖可正常安装,确认package.json的dependencies配置无误。
4. 查看容器启动日志
通过以下命令获取具体的容器启动错误日志,定位更详细的问题原因:
gcloud run logs list --service=mybackend --revision=mybackend-00001-ctc
内容的提问来源于stack exchange,提问作者sumedhe

