Home > Net >  Unable to connect to Postgres within docker
Unable to connect to Postgres within docker

Time:12-13

So I'm trying to dockerize my Postgres-Express-React-Node Application the docker-compose for the application is

version: '3.8'
services:
    postgres:
        image: postgres:12.1
        restart: always
        ports:
            - "5432:5432"
        environment:
            POSTGRES_USER: postgres
            POSTGRES_PASSWORD: PGAdminAth

    backend:
        build: ./backend
        container_name: backend_c
        volumes:
            - /app/node_modules
            - ./backend:/app
        ports:
            - "4000:4000"
    frontend:
        build: ./frontend
        container_name: frontend_c
        ports:
            - "3000:3000"
        stdin_open: true
        tty: true

but every time I run docker-compose up, I get

Error: connect ECONNREFUSED 127.0.0.1:5432
backend_c   |     at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1195:16) {
backend_c   |   errno: -111,
backend_c   |   code: 'ECONNREFUSED',
backend_c   |   syscall: 'connect',
backend_c   |   address: '127.0.0.1',
backend_c   | }

as an error.

The piece of code that connects to my postgres database from nodejs app is

const { Client } = require("pg");

const client = new Client({
  host: "localhost",
  port: 5432,
  user: "postgres",
  password: "PGAdminAth",
  database: "postgres",
});

client.connect();

CodePudding user response:

Docker-compose configures a virtual network where all the containers from compose file live. This:

postgres: # <--- This
    image: postgres:12.1
    restart: always
    ports:
        - "5432:5432"
    environment:
        POSTGRES_USER: postgres
        POSTGRES_PASSWORD: PGAdminAth

means that any service within the virtual network will be able to reach your database by hostname postgres.

So your client code have to use service names when perform network communication to the container.

Hence your client setup would be

const client = new Client({
  host: "postgres",
  port: 5432,
  user: "postgres",
  password: "PGAdminAth",
  database: "postgres",
});

CodePudding user response:

Use depends_on in the backend service. (This started the Database before the backend service.)

depends_on:
    - postgres

And change this

host: "localhost",

to this

host: "postgres",

Inside the application, containers refer to their service name. So use the service name that you gave when defining Database. Examples of service names postgres, backend, and frontend.


To store Database data permanently, you must map a volume to it. Read this

  • Related