Home > Blockchain >  Unable to connect to the database (development). getaddrinfo ENOTFOUND postgres
Unable to connect to the database (development). getaddrinfo ENOTFOUND postgres

Time:01-23

I'm trying to connect to a postgres database with a NestJs app. This is my docker-compose file:

  postgres:
image: postgres:alpine
ports:
  - '5432:5432'
networks:
  - network
#    volumes:
#      - 'postgres_data:/var/lib/postgresql/data'
environment:
  POSTGRES_DB: database
  POSTGRES_USER: postgres
  POSTGRES_PASSWORD: postgres
healthcheck:
  test: ['CMD-SHELL', 'pg_isready -U postgres']
  interval: 10s
  timeout: 5s
  retries: 5

This is my .env file:

TYPEORM_NAME=development
TYPEORM_TYPE=postgres
TYPEORM_HOST=postgres
TYPEORM_PORT=5432
TYPEORM_CACHE=true
TYPEORM_LOGGING=all
TYPEORM_DATABASE=database
TYPEORM_USERNAME=postgres
TYPEORM_PASSWORD=postgres
TYPEORM_DROP_SCHEMA=false
TYPEORM_SYNCHRONIZE=true
TYPEORM_MIGRATIONS_RUN=true

I run: docker exec printenv and I get these:

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=ea6383b9f55f
POSTGRES_PASSWORD=postgres
POSTGRES_DB=database
POSTGRES_USER=postgres
LANG=en_US.utf8
PG_MAJOR=15
PG_VERSION=15.1

When I run npm run start I get this error message:

 Unable to connect to the database (development). Retrying (1)...
Error: getaddrinfo ENOTFOUND postgres
    at GetAddrInfoReqWrap.onlookup [as oncomplete]

What am I doing wrong?

CodePudding user response:

When you run a program on your host, it can't use the hostnames available on the docker network. It has to use 'localhost' and the mapped port(s) of the container.

So

TYPEORM_HOST=postgres

needs to be

TYPEORM_HOST=localhost

Since you've mapped the container port 5432 to the host port 5432, you don't need to change that.

  • Related