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

遵循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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 15:14:58