Skip to content
Latchkey

NestJS "TypeOrmModule ... connection ECONNREFUSED" in CI

TypeOrmModule tried to open a database connection during app startup and the host refused it. In CI this means the database service container is missing or the connection config points at the wrong host.

What this error means

App or test bootstrap fails with "Error: connect ECONNREFUSED 127.0.0.1:5432" from TypeOrmModule while establishing the initial connection.

NestJS
[Nest] ERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)...
Error: connect ECONNREFUSED 127.0.0.1:5432
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16)

Common causes

No database service container in the job

The workflow never started a Postgres/MySQL service, so nothing listens on the configured port.

The host does not match the service networking

Using localhost when the DB runs as a linked service container (or vice versa) makes the connection go to the wrong address.

How to fix it

Add a database service to the job

  1. Declare a services: database with a health check.
  2. Point TypeORM at the host and port the service exposes.
  3. Wait for the service to be healthy before running migrations or tests.
.github/workflows/ci.yml
services:
  postgres:
    image: postgres:16
    env: { POSTGRES_PASSWORD: postgres }
    ports: ['5432:5432']
    options: >-
      --health-cmd="pg_isready" --health-interval=5s --health-retries=5

Match the connection config to CI

Read host and port from env so CI can override them for the service container.

app.module.ts
TypeOrmModule.forRoot({
  type: 'postgres',
  host: process.env.DB_HOST ?? 'localhost',
  port: Number(process.env.DB_PORT ?? 5432),
})

How to prevent it

  • Start a DB service container with a health check for tests that need a database.
  • Drive connection host and port from environment variables.
  • Fail fast with a readiness wait before migrations run.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →