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

Google Cloud VM引入googleapis包后构建时无响应问题求助

NestJS + googleapis 导致Google Cloud VM构建无响应的问题排查与解决

问题概述

在Google Cloud VM上构建NestJS项目时,只要引入googleapis包(v144.0.0),执行npm run build就会导致VM彻底无响应,必须手动重启才能恢复。本地环境构建运行完全正常,注释掉googleapis的导入语句后,VM上也能正常完成构建。

环境信息

  • 系统内存:4GB
  • 架构:x86/64
  • Node.js版本:20.18.1
  • npm版本:10.9.1
  • 包管理器:npm
  • 框架:NestJS
  • 相关依赖:googleapis@144.0.0

问题表现

  • 构建初始阶段流程正常,中途突然无响应
  • 无法通过SSH连接VM,必须手动重启实例才能恢复
  • 因实例直接挂掉,无任何错误日志留存

代码示例

import { BadRequestException, Injectable } from '@nestjs/common';
// import { join } from 'path';
// import { google, sheets_v4 } from 'googleapis';

@Injectable()
export class GoogleSheetsService {
  // private sheets: sheets_v4.Sheets;

  constructor() {
    // const auth = new google.auth.GoogleAuth({
    //   keyFile: join(__dirname, '../../config', 'credentials.json'),
    //   scopes: ['https://www.googleapis.com/auth/spreadsheets'],
    // });
    //
    // this.sheets = google.sheets({ version: 'v4', auth });
  }
}

排查与解决办法

1. 内存耗尽触发OOM Killer(最可能原因)

4GB内存的VM在处理googleapis这类超大型依赖的TypeScript编译时,极易因内存耗尽触发系统OOM Killer,直接终止进程导致实例无响应。

临时解决:修改构建命令,给Node进程分配更多内存:

// package.json
"scripts": {
  "build": "node --max-old-space-size=3072 node_modules/@nestjs/cli/bin/nest.js build"
}

这里分配3GB内存给Node进程,预留1GB给系统基础运行。

长期解决:

  • 升级VM内存到8GB以上
  • 或给VM添加swap分区缓解内存压力:
# 创建4GB swap文件
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
# 设置开机自动挂载swap
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

2. 替换为单个服务的独立客户端包

完整的googleapis包包含了所有Google服务的客户端代码,体积极大,编译时会消耗大量资源。如果只用到Sheets服务,改用独立客户端包可大幅降低资源占用:

npm uninstall googleapis
npm install @googleapis/sheets

修改代码导入:

import { join } from 'path';
import { sheets, Auth } from '@googleapis/sheets';

@Injectable()
export class GoogleSheetsService {
  private sheetsClient: ReturnType<typeof sheets>;

  constructor() {
    const auth = new Auth.GoogleAuth({
      keyFile: join(__dirname, '../../config', 'credentials.json'),
      scopes: ['https://www.googleapis.com/auth/spreadsheets'],
    });

    this.sheetsClient = sheets({ version: 'v4', auth });
  }
}

3. 验证OOM日志

重启VM后,可通过系统日志确认是否为内存问题:

dmesg | grep -i oom

若输出包含Out of memory: Killed process字样,即可确认是内存不足导致的实例挂掉。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 19:03:10