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

使用NestJS、TypeORM与Docker运行数据库迁移时出现EAI_AGAIN错误

错误原因
  • 执行迁移命令的环境和数据库服务所在网络不匹配:你当前是直接在Ubuntu宿主机执行npx typeorm migration:run,配置中的db是Docker Compose为PostgreSQL容器分配的内部服务主机名,仅同属于该Docker自定义网络的容器可以正常解析,宿主机无法识别该域名,因此触发EAI_AGAIN域名解析失败错误。
  • 数据库连接配置存在端口错误:Docker Compose中PostgreSQL服务暴露的端口为5432,但ormconfig.js中配置的端口为5423,即使域名解析正常也会出现连接失败问题。
解决方案

你可以根据自己的使用场景选择以下任意一种方案:

方案1:宿主机直接运行迁移

  1. 修改ormconfig.js中的连接配置,将host改为localhost,同时修正端口为5432,修改后参考如下:
module.exports = {
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: 'pass123',
  database: 'postgres',
  entities: ['dist/**/*.entity.js'],
  migrations: ['dist/migrations/*.js'],
  cli: {
    migrationsDir: 'src/migrations',
  },
};
  1. 确认PostgreSQL容器已经正常启动:
docker-compose up -d db
  1. 重新编译项目后执行迁移命令即可:
npm run build
npx typeorm migration:run

方案2:在Docker容器内运行迁移(适配生产部署逻辑)

  1. 仅需要先修正ormconfig.js中的端口为5432,host保留db即可。
  2. 在docker-compose.yml中补充你的Node应用服务配置,确保应用和数据库服务在同一网络下:
version: "3"
services: 
  db:
    image: postgres
    restart: always
    volumes:
      - mushrooms-psql:/var/lib/postgresql/data
    ports:
      - "5432:5432"
    environment: 
      POSTGRES_PASSWORD: pass123
  app:
    build: .
    ports:
      - "8080:8080"
    depends_on:
      - db
  
volumes:
  mushrooms-psql:
  1. 启动所有服务后进入应用容器内部执行迁移命令:
docker-compose up -d
docker-compose exec app npx typeorm migration:run

兼容多环境的优化建议

你可以通过环境变量动态配置数据库连接参数,比如使用.env文件区分本地环境和容器环境,本地环境配置DB_HOST=localhost,容器环境配置DB_HOST=db,无需手动切换配置。

内容的提问来源于stack exchange,提问作者Ambassador Kosh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:15:03