एरर समाधान · डेवलपर एरर

Node.js "Error: connect ECONNREFUSED" 127.0.0.1: Causes and Fixes

Fix Node.js ECONNREFUSED errors for databases, APIs and localhost: confirm the service listens, handle IPv6 localhost, Docker networking and startup order.

Error messageError: connect ECONNREFUSED 127.0.0.1:5432

लेखक: SiteDownCheck संपादकीय टीम · अपडेट: अक्टूबर 5, 2026 · 5 मिनट पढ़ने में

ECONNREFUSED means your Node.js program tried to open a TCP connection and the target machine immediately refused it, because nothing is listening on that IP address and port. The refusal is fast. This is different from a timeout, where nothing answers at all, and from a DNS failure, where the name never resolved; see Node ENOTFOUND getaddrinfo for that.

You see it when connecting to databases (PostgreSQL on 5432, MySQL on 3306, Redis on 6379, MongoDB on 27017), calling an API on localhost, in tests, and in Docker or CI.

Error: connect ECONNREFUSED 127.0.0.1:5432
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16) {
  errno: -111, code: 'ECONNREFUSED', syscall: 'connect', address: '127.0.0.1', port: 5432
}
Error: connect ECONNREFUSED ::1:3000

The error message includes the exact address and port Node tried, so start by copying them.

Causes, most likely first

  1. The target service is not running, or crashed, or is still starting.
  2. Wrong host or port in your code, config or environment variable (DATABASE_URL, REDIS_HOST).
  3. localhost inside a container pointing at the wrong place. In Docker, localhost is the container itself.
  4. IPv6 versus IPv4 mismatch. localhost resolves to ::1 but the service listens only on 127.0.0.1, or the reverse.
  5. Bound to the wrong interface. The service listens on 127.0.0.1 but you connect from another host or container, so it needs to listen on 0.0.0.0 or a reachable address.
  6. Startup race. Your app starts before the database is ready, a common issue with Docker Compose.
  7. A firewall or security rule rejecting the connection (a drop usually produces a timeout instead).

Step 1: confirm that something listens

From the same machine, check with the tools your system has:

sudo ss -ltnp | grep 5432          # Linux
lsof -iTCP:5432 -sTCP:LISTEN       # macOS and Linux
nc -vz 127.0.0.1 5432              # try to connect
curl -v http://127.0.0.1:3000/     # HTTP service

If nothing is listening, start the service (sudo systemctl start postgresql, docker compose up -d db, redis-server) and read its log for why it stopped. If it is listening on a different port, update your configuration.

Step 2: print what your app is really using

Many ECONNREFUSED bugs come from configuration that is not what you think it is, such as an environment variable that is empty or loaded after the client was created.

console.log('DB target:', process.env.DB_HOST, process.env.DB_PORT);

Make sure your .env loader (dotenv, for example) is called before the code that reads the variables. Ensure the port is a number and the host has no whitespace.

Step 3: IPv6 and localhost

Since Node.js 17, localhost is resolved in the order the system returns, so it can pick ::1 first, whereas older versions preferred IPv4. If your service listens only on IPv4, you may get ECONNREFUSED ::1:PORT. Newer Node versions try multiple addresses by default, which can mask this, but behavior depends on your version, so verify with your own. Quick fixes:

  • Use 127.0.0.1 instead of localhost in the connection settings.
  • Or make the service listen on IPv6 too.
  • Or start Node with --dns-result-order=ipv4first (check your Node version's documentation).

Step 4: Docker and containers

Inside a container, localhost refers to that container, so your app cannot reach a database in another container through it. With Docker Compose, use the service name:

services:
  api:
    build: .
    environment:
      DATABASE_URL: postgres://app:secret@db:5432/appdb
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres:16
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app"]
      interval: 5s
      retries: 10

To reach a service on the host machine from a container, use host.docker.internal (available on Docker Desktop; on Linux add extra_hosts: ["host.docker.internal:host-gateway"]). A service inside a container must listen on 0.0.0.0, not 127.0.0.1, to be reachable from outside that container, and the port must be published for host access. See Docker website down checklist.

Step 5: remote hosts and servers that bind to localhost

PostgreSQL and MySQL listen only on loopback by default on many distributions. For a remote client, change listen_addresses (PostgreSQL) or bind-address (MySQL), open the port only to trusted addresses, and check the firewall. Test from the client host with the पोर्ट चेकर when the target is publicly reachable.

Step 6: add retries for startup races

For services that start together, retry with backoff instead of crashing:

async function connectWithRetry(connectFn, tries = 10) {
  for (let i = 0; i < tries; i++) {
    try { return await connectFn(); }
    catch (err) {
      if (err.code !== 'ECONNREFUSED' || i === tries - 1) throw err;
      await new Promise(r => setTimeout(r, Math.min(1000 * 2 ** i, 15000)));
    }
  }
}

Also handle the 'error' event on streams and clients, or Node may terminate the process with an unhandled error.

How to verify

Run nc -vz HOST PORT and see succeeded, then start your app and confirm the error is gone and a real query or request works. For HTTP services, confirm status with the HTTP स्टेटस चेकर. For public endpoints, use the पोर्ट चेकर and the DNS चेकर to confirm the hostname points at the server you expect. An अपटाइम मॉनिटर on your API's health endpoint catches future crashes.

अगले कदम

सामान्य प्रश्न

What is the difference between ECONNREFUSED and ETIMEDOUT?

Refused means the host answered right away that nothing accepts connections there. Timed out means no answer came back, often from a firewall dropping packets or an unreachable host.

Why does 127.0.0.1 work but localhost fail?

localhost may resolve to ::1 (IPv6) while the service listens only on IPv4. Use the explicit address or make the service listen on both.

Why does my app work locally but not in Docker?

localhost in a container is that container. Use the service name from Compose or host.docker.internal for host services.

Can this be caused by my firewall?

Sometimes. A firewall rule that rejects returns a refusal, while one that silently drops usually causes a timeout. Check iptables, ufw and cloud security groups.

Get notified when this fix updates

Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.

यह पेज सामान्य जानकारी है, जिसे हमारी संपादकीय टीम ने लिखा है और दस्तावेज़ीकरण बदलने पर अपडेट किया जाता है। सर्वर और प्रदाता अलग-अलग होते हैं, इसलिए बदलाव पहले सुरक्षित तरीके से जाँचें। देखें: संपादकीय नीति और अस्वीकरण.