0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I just updated the docker compose file. Please have a look.
You should keep your: ports: - 'X:5432' section to 5432, because Postgres is listening on 5432 on default (5432 is the container side) and X can be anything because it is on the host. When you are using docker-compose for web applications and databases docker ignores the published ports anyways. So you should try these two combinations for your configuration variables: DB_HOST=postgres;DB_PORT=5432; and second one: DB_HOST=app-db;DB_PORT=5432; One of these two should work with your compose file.
Thanks a lot. It solved the problem and is now working.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.