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
- Declare a
services:database with a health check. - Point TypeORM at the host and port the service exposes.
- 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=5Match 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
NestJS TypeORM "No metadata for X was found" (entity glob) in CIFix NestJS TypeORM "EntityMetadataNotFoundError: No metadata for X was found" in CI - the entities glob match…
NestJS "Nest application failed to start" in CIFix "Error: Nest application failed to start" in CI - a lifecycle hook, module init, or async provider threw…
NestJS + Prisma "@prisma/client did not initialize yet" in CIFix NestJS + Prisma "@prisma/client did not initialize yet. Please run prisma generate" in CI - the client wa…