Docker-compose: Node app cannot connect to PostgreSQL DB

Hey everyone,

I have a minimal example with

  • A PostgreSQL DB
  • A Node.js app (with TypeORM)

This is the docker-compose.yml:

version: '3.8'
services:

  app:
    build: .
    ports:
      - "3000:3000"

  db:
    image: postgres:13.9
    healthcheck:
      test: [ "CMD", "pg_isready", "-q", "-d", "docker", "-U", "docker" ]
      timeout: 45s
      interval: 10s
      retries: 10
    restart: always
    environment:
      - POSTGRES_DB=docker
      - POSTGRES_USER=docker
      - POSTGRES_PASSWORD=docker
    ports:
      - 5433:5432

This is the Dockerfile for node app:

FROM node:16

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3000
CMD [ "npm", "run", "start" ]

And here is the connection config in TypeORM:

    type: 'postgres',
    host: 'db',
    port: 5433,
    username: 'docker',
    password: 'docker',
    database: 'docker',

For some reason, I get the following error:

app_1  | Error: connect ECONNREFUSED 172.21.0.2:5433
app_1  |     at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) {
app_1  |   errno: -111,
app_1  |   code: 'ECONNREFUSED',
app_1  |   syscall: 'connect',
app_1  |   address: '172.21.0.2',
app_1  |   port: 5433
app_1  | }

Any suggestions?

lgtm, except port 5433 in your TypeORM. Your ‘app’ service connects to the ‘db’ service using a container network, and such it needs to use the container port 5432 of the postgres database.