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.
By Livops team, the people who build and run LivopsUpdated
The message depends on the language and the driver. A Node app prints:
Error: connect ECONNREFUSED 127.0.0.1:5432
psycopg and other libpq clients print:
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:
const pool = new pg.Pool() // no connectionString: PGHOST or localhost
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:
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
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]:
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]:
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]:
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]:
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:
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
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:
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:
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_URLplusPGHOST,PGPORT,PGUSER,PGPASSWORD,PGDATABASEandPOSTGRES_*for PostgreSQL;MYSQL_URLandMYSQLHOST… for MySQL;REDIS_URLfor Redis;MONGO_URLandMONGODB_URIfor MongoDB. A PostgreSQL URL looks likepostgresql://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
startprojectgetsmanage.py migratebefore 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 inDATABASE_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, and the variables in 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
- Node.js docs — Errors, common system errors (nodejs.org). Checked .
- node-postgres — Connecting (node-postgres.com). Checked .
- PostgreSQL docs — libpq connection strings (postgresql.org). Checked .
- Prisma docs — PostgreSQL (prisma.io). Checked .
- Prisma docs — Connection pool (prisma.io). Checked .
- Psycopg 3 — Connection classes (psycopg.org). Checked .
- SQLAlchemy 2.0 — Engine configuration (docs.sqlalchemy.org). Checked .
- SQLAlchemy 2.0 — PostgreSQL dialect (docs.sqlalchemy.org). Checked .
- Django docs — Settings (docs.djangoproject.com). Checked .
- Django docs — Databases (docs.djangoproject.com). Checked .
- redis-py — Connecting to Redis (redis.readthedocs.io). Checked .
- PostgreSQL docs — pg_isready (postgresql.org). Checked .
- PostgreSQL docs — Connections and authentication (postgresql.org). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy with a databaseRelated
- Managed PostgreSQL hosting in 2026: the options comparedA production PostgreSQL needs backups you can restore, a connection limit your app stays under, the app in the same region, and a supported version. On Livops a PostgreSQL 15, 16 or 17 database runs inside your project, its DATABASE_URL is written into your services, and it is backed up every night; 500 MB is free, one per team, and 1 GB is 9 credits a month. Here is how Neon, Supabase, Render, Railway and a VPS compare.
- App not listening on $PORT: why the health check failed after deployThe platform started your app, tried the port it gave it, and nothing answered in time. Almost always the app listens on its own fixed port instead of the PORT variable, listens on localhost (127.0.0.1) instead of 0.0.0.0, or crashed or was still starting when the check gave up. Listen on 0.0.0.0 and the port in PORT, and it passes.
- Gunicorn "Worker failed to boot": what it means and how to fix itGunicorn's worker could not load your application, so the master process shut down. The cause is the Python traceback printed just above the message: most often a missing package or variable, or a wrong module:variable path in the gunicorn command. Fix what the traceback names and the workers boot.
- DisallowedHost: Invalid HTTP_HOST header — Django's 400 Bad RequestDjango received a request for a host name that is not in ALLOWED_HOSTS, so it answered 400 Bad Request. Add the domain the site is served on to ALLOWED_HOSTS, without https:// and without a port, or read the list from an environment variable, and redeploy.
- A staging environment next to productionOn Livops, Add environment on the project page makes a staging copy of your production services, each with its own address, its own variables and its own empty database, so a test never touches production data. Promote to production then ships the exact release you tested, without rebuilding. A staging environment costs half; pull request previews are billed like regular services.
- Django hosting in 2026: how to deploy a Django app, and whereA Django app in production needs a WSGI or ASGI server instead of runserver, DEBUG off, ALLOWED_HOSTS set, collected static files and migrations on every deploy. On Livops a repository with manage.py and requirements.txt gets all of that from a push, for 39 credits a month (39,000 so'm). Here is how Render, Railway, Fly.io and a VPS compare.