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

NestJs项目启动出现AggregateError,求排查与解决方法

Nest.js + TypeORM + PostgreSQL启动时出现AggregateError的排查方案

问题背景

基于Nest.js、TypeORM和PostgreSQL的后端项目此前运行正常,近期未修改代码的情况下启动应用时出现以下错误:

[10:23:44 AM] Starting compilation in watch mode...

[10:23:49 AM] Found 0 errors. Watching for file changes.

[info] [NestFactory] [9/6/2023, 10:23:51 AM] => Starting Nest application... (+0ms)
[info] [InstanceLoader] [9/6/2023, 10:23:51 AM] => PassportModule dependencies initialized (+40ms)
[info] [InstanceLoader] [9/6/2023, 10:23:51 AM] => TypeOrmModule dependencies initialized (+0ms)
[info] [InstanceLoader] [9/6/2023, 10:23:51 AM] => AppModule dependencies initialized (+0ms)
AggregateError: 
    at internalConnectMultiple (node:net:1114:18)
    at afterConnectMultiple (node:net:1667:5)

已尝试的操作:

  • 重启应用,无效
  • 核对TypeORM中PostgreSQL的主机、端口等凭证,确认无误
  • 排查近期代码变更,未发现相关问题

可能成因

  1. PostgreSQL服务异常:数据库服务未启动、端口被其他程序占用
  2. 连接超时/重试聚合错误:TypeORM的连接超时设置过短,多次连接失败后触发AggregateError
  3. 网络或权限拦截:本地防火墙/安全软件拦截连接,或PostgreSQL的访问控制配置拒绝当前应用
  4. 依赖版本兼容性:Node.js、pg或typeorm版本更新后出现兼容性问题

解决步骤

1. 验证PostgreSQL服务状态

  • 检查服务是否运行:
    • Windows:sc query postgresql-x64-15(替换为你的PostgreSQL版本)
    • Linux/macOS:sudo systemctl status postgresql
  • 启动服务(若未运行):
    • Windows:sc start postgresql-x64-15
    • Linux/macOS:sudo systemctl start postgresql
  • 检查端口占用:
    • macOS/Linux:lsof -i :5432,确认5432端口被PostgreSQL进程占用
    • Windows:netstat -ano | findstr :5432,查看PID对应进程是否为PostgreSQL

2. 调整TypeORM连接配置

修改TypeORM的连接参数,延长超时时间并优化重试逻辑:

// app.module.ts 或 ormconfig.ts
TypeOrmModule.forRoot({
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'your_username',
  password: 'your_password',
  database: 'your_db_name',
  entities: [/* 你的实体类 */],
  synchronize: true, // 根据你的需求调整
  connectTimeoutMS: 10000, // 延长连接超时至10秒
  retryAttempts: 2, // 减少重试次数
  retryDelay: 1500, // 重试间隔1.5秒
})

3. 排查网络与数据库权限

  • 临时关闭本地防火墙、杀毒软件,测试应用是否能正常启动
  • 检查PostgreSQL的pg_hba.conf配置文件,确保允许当前主机访问:
    添加或修改如下条目(替换为你的数据库和用户名):
    host    your_db_name    your_username    127.0.0.1/32    scram-sha-256
    host    your_db_name    your_username    ::1/128         scram-sha-256
    
    修改后重启PostgreSQL服务生效

4. 回退兼容的依赖版本

如果近期升级过Node.js或依赖包,尝试回退到之前稳定的版本:

  1. 查看当前依赖版本:npm list pg typeorm
  2. 安装已知兼容的版本:
    npm install pg@8.11.0 typeorm@0.3.17
    
  3. 清理并重新安装依赖:
    rm -rf node_modules package-lock.json
    npm install
    

内容的提问来源于stack exchange,提问作者Salih Burak Çoşkun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 12:35:17