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();
2
Answers
Docker-compose configures a virtual network where all the containers from compose file live. This:
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
Use
depends_on
in thebackend
service. (This started the Database before thebackend
service.)And change this
to this
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.