EN VI

Node.js - Keep getting the Error: getaddrinfo ENOTFOUND postgres when I try to connect to docker container?

2024-03-11 01:30:06
Node.js - Keep getting the Error: getaddrinfo ENOTFOUND postgres when I try to connect to docker container

I keep getting this error through my typeORM DataSource connection when I'm trying to connect to my dockerized postgres database.

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

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

What I have tried so far:

  1. connect to the postgresql through the terminal with psql -h localhost --port 5432 -U postgres => worked !
  2. check that the node app is started depends on postgres service healthiness
  3. check that I have only one postgres service running on port 5432 with lsof -i :5432 => com.docke 27212 sbagherzadeh 329u IPv6 0x81fea2c6d7e20ca9 0t0 TCP *:postgresql (LISTEN)
  4. check that I request the container name instead of localhost or 127.0.0.1
  5. try to use a .env file instead of the env variables directly from the docker compose file.

I'm running out of solutions if someone can help please :) !

Solution:

postgres is on the postgres-db-network but node_app is not. so they're not networked together. So they can't talk. Thus, docker does not expose their container names to each other as resolvable hostnames.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login