1

I have the next docker-compose file:

version: "3"

services:
  proxy:
    build:
      context: ./client
      dockerfile: proxy.Dockerfile
    ports:
      - "80:80"
  server:
    build:
      context: .
      dockerfile: server.Dockerfile
    ports:
      - "3000:3000"
    depends_on: [db]
  db:
    image: postgres
    environment:
      POSTGRES_USER: lautidamo
      POSTGRES_PASSWORD: la12papa
      POSTGRES_DB: product-manager
    ports:
      - "5432:5432"

And i have this database.ts:

import { Sequelize } from "sequelize";

export const sequelize = new Sequelize(
  "product-manager",
  "lautidamo",
  "la12papa",
  {
    dialect: "postgres",
    host: "localhost",
    port: 5432
  }
);

The proxy and the server services works fine. But when I make a request to a route where have to connect to the database, i have this error connect ECONNREFUSED 127.0.0.1:5432.

ldamore
  • 71
  • 3

1 Answers1

2

Don't connect to localhost. Connect to the name of your database service. In your case that would be db.

That looks like this:

export const sequelize = new Sequelize(
  "product-manager",
  "lautidamo",
  "la12papa",
  {
    dialect: "postgres",
    host: "db",
    port: 5432
  }
);

EDIT: Also, a couple of points...

  1. You don't need that ports option in your db service unless you want to connect to it externally. That is to say, you only need that in there if you want to connect to the database container using something external to the composition like dbeaver or some kind of database management tool. If you're just connecting to it with other containers in the composition like your app, you can leave that out.

  2. I think you could put those DB credentials in .env file next to your docker-compose.yml. Provided you add them to your server service definition - you could then just access those values using process.env.POSTGRES_USER etc. :)

robertmain
  • 409
  • 7
  • 22
  • 1
    Thanks for the reply! When I get home I´ll try it. On point 2, I was trying to connect hardcode first before getting into the environment variables because I was already going crazy trying to connect – ldamore Jan 24 '20 at 14:13
  • No problem. Yeah, that makes sense to do that first :) – robertmain Jan 24 '20 at 14:39
  • @robertmain How to use both db and localhost if I want the flexibility to use docker-compose / standalone running – Vignesh S May 04 '22 at 16:55
  • @VigneshS You probably want to use environment variables in your code (`process.env.DB_USERNAME`) and then pass this into your docker container using docker-compose....or set it directly on the command line when running your app without docker. – robertmain May 08 '22 at 15:45