# ECONNREFUSED / Connection refused: why the app cannot reach its database after deploy

> Nothing was listening at the address your app tried. When the address is 127.0.0.1 or localhost, the app never read the database's real address: DATABASE_URL is not set, is not read, or is read during a build that has no database. Attach the database, read DATABASE_URL (or REDIS_URL, MYSQL_URL) at runtime, run migrations before the start rather than in the build, and keep the connection pool under the server's limit.

Source: https://livops.dev/en/guides/error-econnrefused-database

By Livops team, the people who build and run Livops. Updated 20 November 2026.

The message depends on the language and the driver. A Node app prints:

```text
Error: connect ECONNREFUSED 127.0.0.1:5432
```

psycopg and other libpq clients print:

```text
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
        Is the server running on that host and accepting TCP/IP connections?
```

and older versions say `could not connect to server: Connection refused`. With Redis it ends in `:6379`, with MySQL in `:3306`. This page explains what the error means, lists the causes from the most common, shows the fix for node-postgres, Prisma, psycopg, SQLAlchemy, Django and Redis, and says how a database is attached on Livops.

## What does the error mean?

`ECONNREFUSED` means the target machine actively refused the connection, which usually happens when nothing is running at that address on that host[1]. So the network worked; the app reached a host, and no database was listening on the port it asked for.

Read the address in the message first. **`127.0.0.1`, `::1` or `localhost`** means the app looked for the database inside its own container — it never got, or never used, the database's real address. **Any other host** means it read an address, and that address is wrong, not reachable from where the app runs, or the database there is not up.

`ETIMEDOUT` is a different failure: the other side did not respond in time[1]. `ENOTFOUND` is a DNS failure: the host name did not resolve[1].

## Causes, most common first

### 1. The app falls back to localhost

Nearly every client has a default host, and it is the local machine. node-postgres defaults to `PGHOST=localhost` and `PGPORT=5432`[2]. libpq with no host connects to a Unix-domain socket in `/tmp`[3]. Django's empty `HOST` means localhost[9]. redis-py defaults to `localhost` and `6379`[11]. So code like this works on your laptop and fails after a deploy:

```js
const pool = new pg.Pool()   // no connectionString: PGHOST or localhost
```

```python
DATABASE_URL = os.environ.get("DATABASE_URL", "postgresql://localhost/app")
```

The fix is to read the platform's variable, and to fail loudly when it is missing rather than quietly try localhost:

```python
DATABASE_URL = os.environ["DATABASE_URL"]   # KeyError names the missing variable
```

### 2. DATABASE_URL is not set

The database was never attached to the project, the variable has another name in your code (`DB_URL`, `POSTGRES_URL`), or it lives in a `.env` file, which is usually kept out of the repository and so never reaches the server. Put the value in the platform's variables, or attach a database so the platform writes it for you, under the name your code reads.

### 3. The build connects to the database

Migrations in the build command (`prisma migrate deploy && next build`), a static page that queries the database while it renders, a Django `manage.py migrate` in the build: a build often runs where no database is reachable, and on Livops the build has no database at all. Run migrations as a step before the start — the pre-deploy command on Livops — and query the database at request time, not at build time.

### 4. The address is right, but not from here

A database's internal host name works only inside its own private network. On Livops the host is `postgres` (or `redis`, `mysql`), and it resolves only inside the project; an app hosted somewhere else cannot reach it. The reverse is true too: an address copied from a Docker Compose file on your laptop (`db:5432`) means nothing on the server.

### 5. An SSL setting that does not match

This shows up as an SSL error rather than "connection refused", but it is often mixed up with it. libpq's default `sslmode` is `prefer`: try SSL, then fall back to a plain connection[3]. `require` allows only SSL, and `verify-full` also checks the certificate and the host name[3]; Prisma reads the same `sslmode` parameter in the URL[4]. A connection string copied from a hosted provider often carries `sslmode=require`. Use the URL your platform gives you as it is, and add SSL settings only when the database's provider asks for them.

### 6. Too many connections

When every connection slot is taken, the server refuses the next client with a "too many clients" error rather than `ECONNREFUSED`, but the app is just as broken. PostgreSQL's own default is 100 connections, three of them kept for superusers[13], and small hosted databases allow fewer. Pools add up: Prisma 7 with the `pg` adapter opens up to 10 per process by default[5], and SQLAlchemy keeps 5 with 10 more in overflow[7]. Multiply by the number of processes and size each pool to fit.

### 7. The database is restarting

A database that restarts drops every connection, and a client that holds on to a dead one fails on its next query. SQLAlchemy's `pool_pre_ping` tests each connection when it is checked out[7]; Django's `CONN_HEALTH_CHECKS` checks a persistent connection before reuse[9]. Retrying the first connection a few times at startup, with a pause, covers the case where the app starts before the database is ready.

## The fix, per stack

### Node: node-postgres

```js
import pg from 'pg'

const pool = new pg.Pool({
  connectionString: process.env.DATABASE_URL,   // postgresql://user:pass@host:5432/db
  max: 5,
})
```

node-postgres accepts the URL as `connectionString`, for both `Pool` and `Client`[2].

### Node: Prisma

Prisma 7 reads the URL in `prisma.config.ts` for the CLI[4]:

```ts
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'

export default defineConfig({
  schema: 'prisma/schema.prisma',
  datasource: { url: env('DATABASE_URL') },
})
```

and the client connects through the `pg` driver adapter[4], whose `max` sets the pool size[5]:

```ts
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from './generated/prisma/client'

const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL, max: 5 })
export const prisma = new PrismaClient({ adapter })
```

On Prisma 6 the pool size is the `connection_limit` parameter in the URL[5]: `?connection_limit=5`. Run `prisma migrate deploy` before the start, not in the build.

### Python: psycopg

`psycopg.connect()` takes a `postgresql://` URL or `key=value` pairs as its first argument[6]:

```python
import os
import psycopg

conn = psycopg.connect(os.environ["DATABASE_URL"])
```

### Python: SQLAlchemy

A plain `postgresql://` URL makes SQLAlchemy use psycopg2[7]. If you installed psycopg 3, name the driver in the scheme, `postgresql+psycopg://`[8]:

```python
import os
from sqlalchemy import create_engine

url = os.environ["DATABASE_URL"].replace("postgresql://", "postgresql+psycopg://", 1)
engine = create_engine(url, pool_size=5, max_overflow=0, pool_pre_ping=True)
```

### Django

Django does not read `DATABASE_URL` by itself, and an empty `HOST` means localhost[9], so set every field from the environment. The `PG*` variables carry the same address in parts:

```python
import os

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "HOST": os.environ["PGHOST"],
        "PORT": os.environ["PGPORT"],
        "NAME": os.environ["PGDATABASE"],
        "USER": os.environ["PGUSER"],
        "PASSWORD": os.environ["PGPASSWORD"],
        "CONN_HEALTH_CHECKS": True,
    }
}
```

`CONN_MAX_AGE` defaults to 0, a new connection per request[9]. With psycopg 3 and `psycopg[pool]` installed, `"OPTIONS": {"pool": True}` turns on Django's own connection pool, which needs `CONN_MAX_AGE` at 0[10].

### Redis

```python
import os
import redis

r = redis.Redis.from_url(os.environ["REDIS_URL"])
```

`redis://` is a plain TCP connection and `rediss://` one wrapped in SSL[11].

## How to confirm the fix

First, print the host the app will use, without the password:

```sh
node -e 'console.log(new URL(process.env.DATABASE_URL).host)'
python -c 'import os, urllib.parse; print(urllib.parse.urlsplit(os.environ["DATABASE_URL"]).netloc.split("@")[-1])'
```

If that prints `localhost`, or fails because the variable is empty, the variable is the problem, not the network. Then check the server answers at that address:

```sh
pg_isready -d "$DATABASE_URL"
```

`pg_isready` takes a connection string in `-d` and exits with 0 when the server accepts connections, 1 when it is rejecting them, for example while starting, and 2 when nothing responded[12].

## On Livops

- **Attach the database to the project.** Under **Databases**, add PostgreSQL (15, 16 or 17), MySQL (8.0 or 8.4), Redis 7 or MongoDB (7 or 8.0). It runs in its own container inside the project environment.
- **The variables are written for you**, to every service in the environment, including ones added later: `DATABASE_URL` plus `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE` and `POSTGRES_*` for PostgreSQL; `MYSQL_URL` and `MYSQLHOST`… for MySQL; `REDIS_URL` for Redis; `MONGO_URL` and `MONGODB_URI` for MongoDB. A PostgreSQL URL looks like `postgresql://app:<password>@postgres:5432/app`.
- **Variables take effect on the next deploy.** After adding a database or changing a variable, deploy again, or restart the service to apply them now.
- **The build has no database.** Put migrations in the **pre-deploy command**: it runs before each new version starts, and if it fails, the old version keeps serving. A Django project laid out by `startproject` gets `manage.py migrate` before every start without it.
- **There is no public port.** The host is an internal name such as `postgres`, reachable only from services in the project. Your computer reaches it through **Connect from your computer** and an SSH tunnel signed by your key.
- **Connection limits.** PostgreSQL accepts 20 connections at once, MySQL 30, and a built-in pooler is not offered yet: keep pools small, for example `max: 5`.
- **Staging has its own database.** A new environment gets an empty database of each type production has; variables that cannot be copied show as **not set** until you fill them in.
- **A failed start keeps the old version.** The deploy fails as `start_failed`, the app's last lines are on the **Logs** page, and a web app's previous version keeps serving. The error's **Details** link leads to the docs for this case — add a database to the project, or put an external database's address in `DATABASE_URL` — and the assistant button next to the failed deploy explains what to change.

The same case in the docs: [The app waits for a database](https://livops.dev/en/docs/error-start#waits-for-database), and the variables in [Databases](https://livops.dev/en/docs/databases). A database is free at 500 MB, one per team; 1 GB is 9 credits a month.

## Questions

**Why does it work on my machine?**

On your machine the database runs on the same computer, so localhost reaches it. After a deploy the app runs in its own container, where localhost is the container itself and no database is listening there. The database has its own host name, which the platform gives you in DATABASE_URL.

**What does 127.0.0.1:5432 in the error tell me?**

That the app tried to reach PostgreSQL inside its own container, which almost always means it never read the real address. 5432 is PostgreSQL's port, 3306 MySQL's and 6379 Redis's. If the error shows another host, the address was read, and that host is wrong or unreachable.

**Is ECONNREFUSED the same as a timeout or ENOTFOUND?**

No. ECONNREFUSED means the host answered and nothing was listening on that port. ETIMEDOUT means nothing answered in time, often a firewall or a host the app cannot route to. ENOTFOUND means the host name could not be resolved at all.

**Do I need sslmode=require for a Livops database?**

Keep DATABASE_URL as Livops writes it. The database is reached on the project's internal network at the host postgres and has no public port. Add SSL settings only for an external database whose provider asks for them.

**I added a database and still get the error. Why?**

Variables reach a service when it starts. Deploy again or restart the service so it picks up DATABASE_URL. Also check that the error is not from the build: the build has no database, so migrations and queries belong in the pre-deploy command or at runtime.

**Can an app hosted elsewhere connect to a Livops database?**

No. A Livops database has no public port and is reachable only from services in its own project, and from your computer through an SSH tunnel. Run the app on Livops too, or use a database with a public address.

## Sources

1. [Node.js docs — Errors, common system errors](https://nodejs.org/api/errors.html). Checked 20 November 2026.
2. [node-postgres — Connecting](https://node-postgres.com/features/connecting). Checked 20 November 2026.
3. [PostgreSQL docs — libpq connection strings](https://www.postgresql.org/docs/current/libpq-connect.html). Checked 20 November 2026.
4. [Prisma docs — PostgreSQL](https://www.prisma.io/docs/orm/overview/databases/postgresql). Checked 20 November 2026.
5. [Prisma docs — Connection pool](https://www.prisma.io/docs/orm/prisma-client/setup-and-configuration/databases-connections/connection-pool). Checked 20 November 2026.
6. [Psycopg 3 — Connection classes](https://www.psycopg.org/psycopg3/docs/api/connections.html). Checked 20 November 2026.
7. [SQLAlchemy 2.0 — Engine configuration](https://docs.sqlalchemy.org/en/20/core/engines.html). Checked 20 November 2026.
8. [SQLAlchemy 2.0 — PostgreSQL dialect](https://docs.sqlalchemy.org/en/20/dialects/postgresql.html). Checked 20 November 2026.
9. [Django docs — Settings](https://docs.djangoproject.com/en/stable/ref/settings/). Checked 20 November 2026.
10. [Django docs — Databases](https://docs.djangoproject.com/en/stable/ref/databases/). Checked 20 November 2026.
11. [redis-py — Connecting to Redis](https://redis.readthedocs.io/en/stable/connections.html). Checked 20 November 2026.
12. [PostgreSQL docs — pg_isready](https://www.postgresql.org/docs/current/app-pg-isready.html). Checked 20 November 2026.
13. [PostgreSQL docs — Connections and authentication](https://www.postgresql.org/docs/current/runtime-config-connection.html). Checked 20 November 2026.
