Wai Yan Hein
Wai Yan Hein

Reputation: 14771

Unable to connect to the Postgres database in Docker Compose

I am building a Node JS Web application. I am using Postgres SQL and Sequelize for the database.

I have the docker-compose.yaml with the following content.

    version: '3.8'

services:
  web:
    container_name: web-server
    build: .
    ports:
      - 4000:4000
    restart: always
    depends_on:
      - postgres
  postgres:
    container_name: app-db
    image: postgres:11-alpine
    ports:
      - '5431:5431'
    environment:
      - POSTGRES_USER=docker
      - POSTGRES_PASSWORD=secret
      - POSTGRES_DB=babe_manager
    volumes:
      - ./postgres-data:/var/lib/postgresql/data
    build:
      context: .
      dockerfile: ./pgconfig/Dockerfile
volumes:
  app-db-data:

I am using the following credentials to connect to the database.

DB_DIALECT=postgres
DB_HOST=postgres
DB_NAME=babe_manager
DB_USERNAME=docker
DB_PORT=5431
DB_PASSWORD=secret

When the application tries to connect to the database, I am getting the following error.

getaddrinfo ENOTFOUND postgres

I tried using this too.

 DB_DIALECT=postgres
    DB_HOST=localhost
    DB_NAME=babe_manager
    DB_USERNAME=docker
    DB_PORT=5431
    DB_PASSWORD=secret

This time I am getting the following error.

connect ECONNREFUSED 127.0.0.1:5431

My app server is not within the docker-compose.yaml. I just start it using "nodemon server.js". How can I fix it?

Upvotes: 0

Views: 1378

Answers (1)

matic1123
matic1123

Reputation: 1119

You need to make sure your Postgres container and your Node are on the same network. After they reside in the common network you can then use docker's DNS to resolve the database from the Node application in your case eighter postgres or test-db for hostname should work. More on container communication over docker networks.

Upvotes: 1

Related Questions