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

连接Docker化PostgreSQL时TypeORM报getaddrinfo ENOTFOUND postgres错误求助

问题描述

使用TypeORM的DataSource连接Docker部署的PostgreSQL数据库时,持续出现DNS解析失败错误,相关信息如下:

Docker Compose配置

node_app:
  build: ./node
  container_name: node
  environment:
    - PGHOST=postgres
    - NODE_ENV=development
    - PORT=4000
  depends_on:
    postgres:
      condition: service_healthy
  command: sh -c "npm start"
  volumes:
    - ./node:/home/node/app:cached
  ports:
    - '4000:4000'
postgres:
  image: postgres
  container_name: postgres
  restart: always
  environment:
    POSTGRES_DB: job_matching
    POSTGRES_USER: postgres
    POSTGRES_PASSWORD: password
  ports:
    - 5432:5432
  volumes:
    - ./pgdata:/var/lib/postgresql/data
    - ./db/init.sql:/docker-entrypoint-initdb.d/create_tables.sql
  networks:
    - postgres-db-network
  healthcheck:
    test: ["CMD-SHELL", "pg_isready -d $${POSTGRES_DB} -U $${POSTGRES_USER}"]
    interval: 1s
    timeout: 5s
    retries: 10

TypeORM数据源配置(app.ts)

const dataSource = new DataSource({
  type: 'postgres',
  host: process.env.PGHOST || 'localhost',
  port: 5432,
  username: 'postgres',
  password: 'password',
  database: 'job_matching',
  entities: ['src/models/**/*.ts'],
});

错误信息

Error during Data Source initialization Error: getaddrinfo ENOTFOUND postgres
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (node:dns:118:26) {
  errno: -3008,
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'postgres'
}

已尝试的解决方法

  • 通过终端执行psql -h localhost --port 5432 -U postgres成功连接PostgreSQL
  • 配置Node应用依赖PostgreSQL服务健康状态启动
  • 使用lsof -i :5432确认端口5432仅PostgreSQL服务运行
  • 已使用容器名称postgres而非localhost/127.0.0.1作为连接地址
  • 尝试用.env文件替代docker-compose直接设置环境变量

解决方案

该错误核心原因是Node容器与PostgreSQL容器不在同一个Docker网络内,导致无法通过容器名称解析地址。

修复步骤:

  1. 给node_app服务添加相同的网络配置,与PostgreSQL共享postgres-db-network:
    修改docker-compose.yml中的node_app部分,新增networks字段:
    node_app:
      # 原有配置保持不变
      networks:
        - postgres-db-network
    
  2. 重新启动服务:
    docker-compose down
    docker-compose up -d --build
    

验证方法:

进入Node容器内部,测试与PostgreSQL容器的连通性:

docker exec -it node ping postgres

如果能正常ping通,说明网络配置生效,TypeORM连接问题将同步解决。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 00:10:25