0

If we'll set the host setting to localhost as below

import type { PostgresConnectionOptions } from "typeorm/driver/postgres/PostgresConnectionOptions";

export default function generateTypeORM_Configuration(): PostgresConnectionOptions {
  return {
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "postgres",
    password: "pass1234",
    entities: []
  };
}

we could deal with

Error: connect ECONNREFUSED 127.0.01:5432

because of the loopback adapter. This problem has been discussed in ECONNREFUSED for Postgres on nodeJS with dockers topics.

However if to replace the localhost with Docker service name:

{
    type: "postgres",
    host: "Database",
    port: 5432,
    username: "postgres",
    password: "pass1234",
    entities: [ MemberModel ]
}
version: "3.5"

services:

  Database:

    image: postgres
    container_name: Example-Local-Database
    ports:
      - "${DATABASE_PORT}:${DATABASE_PORT}"

    environment:
      - "POSTGRES_PASSWORD=${DATABASE_PASSWORD}"

    volumes:
      - DatabaseData:/var/lib/postgresql/data

  # ...

volumes:
  DatabaseData:
    name: Example-Local-DatabaseData
    driver: local

we'll face with

getaddrinfo ENOTFOUND Database

error if try to run the migration. In the topics "getaddrinfo ENOTFOUND Database" when try to connect with Database from TypeORM CLI while basically connection is fine I have been told to set host to localhost - back to square one. Of course I have tried to comment about it in this topics before create new question.

Takeshi Tokugawa YD
  • 670
  • 5
  • 40
  • 124

1 Answers1

1

Since you're setting up your database configuration in code, it should be straightforward to use an environment variable there. A Compose environment: block can then set its value to a Compose-specific value. I like to set these up so that, if the environment variable isn't set, it uses a reasonable developer-friendly default.

So you might set for example

export default function generateTypeORM_Configuration(): PostgresConnectionOptions {
  return {
    type: "postgres",
    host: process.env.DB_HOST || "localhost",
    ...
  }
}

If you just run this locally, $DB_HOST won't be set and it will fall back to localhost. In Compose you need to set that environment variable

version: '3.8'
services:
  app:
    build: .
    environment:
      DB_HOST: database
  database:
    image: postgres

This same approach will work in other environments. Imagine using a hosted Amazon RDS database in production, for example; you'd just need to plug in the database's host name as an environment variable and not need to actually change your application at all to use that.

David Maze
  • 130,717
  • 29
  • 175
  • 215