当我尝试连接到 docker 容器时,不断收到错误:getaddrinfo ENOTFOUND postgres

问题描述 投票:0回答:1

当我尝试连接到我的 dockerized postgres 数据库时,我不断通过 typeORM DataSource 连接收到此错误。

docker-compose.yml

  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

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'],
});

docker 中的错误

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'
}

到目前为止我尝试过的

  1. 通过终端连接到 postgresql
    psql -h localhost --port 5432 -U postgres
    => 成功了!
  2. 检查节点应用程序是否启动取决于 postgres 服务的健康状况
  3. 检查我是否只有一个 postgres 服务在端口 5432 上运行
    lsof -i :5432
    =>
    com.docke 27212 sbagherzadeh  329u  IPv6 0x81fea2c6d7e20ca9      0t0  TCP *:postgresql (LISTEN)
  4. 检查我是否请求容器名称而不是
    localhost
    127.0.0.1
  5. 尝试使用 .env 文件而不是直接来自 docker compose 文件的 env 变量。

如果有人可以帮忙,我已经没有解决方案了:)!

node.js postgresql docker docker-compose typeorm
1个回答
0
投票

postgres
位于
postgres-db-network
上,但
node_app
不在。所以他们没有联网。所以他们不能说话。因此,docker 不会将它们的容器名称作为可解析的主机名相互公开。

© www.soinside.com 2019 - 2024. All rights reserved.