0

So I have an application that uses express, Postgres and pgweb. They work fine on their own but i get the following error when accessing the database from express:

postgres_db_1  | 2021-11-23 13:08:59.474 UTC [1] LOG:  database system is ready to accept connections
app_1          | /usr/src/app/helpers/queries.js:7
app_1          |         if (error) throw error
app_1          |                    ^
app_1          |
app_1          | Error: connect ECONNREFUSED 127.0.0.1:5432
app_1          |     at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16) {
app_1          |   errno: -111,
app_1          |   code: 'ECONNREFUSED',
app_1          |   syscall: 'connect',
app_1          |   address: '127.0.0.1',
app_1          |   port: 5432
app_1          | }

My docker-compose file:

version: "3.9"

services:
  postgres_db:
    image: postgres
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    ports:
      - "5432:5432"

  pgweb:
    image: sosedoff/pgweb
    restart: unless-stopped
    environment:
      - DATABASE_URL=postgres://postgres:postgres@postgres_db:5432/postgres?sslmode=disable
    ports:
      - "8081:8081"
    depends_on:
      - postgres_db

  app:
    image: node
    build: ./API/
    restart: always
    volumes:
      - .:/app/
      - /app/node_modules
    ports:
      - "3001:3001"
    depends_on:
      - postgres_db

And my connection config in express:

module.exports = {
    user: 'postgres',
    host: 'localhost',
    database: 'postgres',
    password: 'postgres',
    port: 5432,
}

1 Answers1

0

In Docker, you should connect to a container by its name. Specifically, the host of your Postgres is postgres_db instead of localhost. You need to modify your config from host: 'localhost' to host: 'postgres_db'.

Besides, if your Postgres is not intended to be public, you don't need to publish its port by - "5432:5432".

minhuw
  • 429
  • 3
  • 10