THE PRACTICAL STACK RESEARCH DESK · STEP-BY-STEP BLUEPRINTS, CLI COMMANDS & VERIFIED BENCHMARKS

THE PRACTICAL STACK

How-To Guides · Verified AI Benchmarks · Step-by-Step Fixes

How to Fix ECONNREFUSED 127.0.0.1:5432 / ::1:6379 & Perpetual Docker Container Restart Loops (Exit Codes 0, 1, 137): Root Causes & Step-by-Step Fixes

Key Takeaways & Implementation Summary ✓ Verified Q4 2026
  • Hands-On Methodology: Verified against live vendor documentation, actual API rate-limit headers, and reproducible terminal output.
  • Actionable Deliverables: Includes full pricing and quota comparison tables, annotated configuration walkthroughs, and 1-click copyable CLI commands.
  • Zero Sponsorship Bias: Independent engineering research by The Practical Stack Research Desk with zero paid placement.
How to Fix ECONNREFUSED 127.0.0.1:5432 / ::1:6379 & Perpetual Docker Container Restart Loops (Exit Codes 0, 1, 137): Root Causes & Step-by-Step Fixes

When a Node.js, Python, or Go container works locally on your laptop but enters a perpetual Restarting (1) loop the moment you deploy it via Docker Compose—flooding logs with Error: connect ECONNREFUSED 127.0.0.1:5432 (PostgreSQL) or ECONNREFUSED ::1:6379 (Redis)—do not waste time debugging your database server. As explained in Runsite's ECONNREFUSED Deployment Guide and the DEV Community Docker Restart Diagnosis Guide, 127.0.0.1 and IPv6 ::1 inside a container refer to the application container's own isolated network namespace, meaning your app is trying to connect to itself.

Fast Diagnosis: Freeze the restart loop with docker update --restart=no <container>, inspect the numeric exit code (`1` = app error, `137` = Linux OOM kill, `0` = foreground process exited), replace `localhost`/`127.0.0.1` with the Docker Compose service hostname (`db` or `cache`), and gate startup on `condition: service_healthy`. For Nginx upstream drops, see our companion 502 Bad Gateway troubleshooting guide and Problem and Solution archive.

1. Root Cause Matrix: Matching Exit Codes & Loopback Signatures

Match your exact container log signature and exit code in the table below (Runsite; DEV Community; Docker Forums):

Error Signature / Exit Code Why It Happens 60-Second Verification Command Permanent Fix
ECONNREFUSED 127.0.0.1:5432 or 127.0.0.1:6379 DATABASE_URL or REDIS_URL is missing in container env, causing node-postgres or ioredis to default silently to 127.0.0.1 (Runsite) docker exec my-app printenv | grep -E 'DATABASE_URL|REDIS_URL' Point env vars to Docker Compose service names (postgresql://db:5432, redis://cache:6379) and fail fast if unset (Runsite)
ECONNREFUSED ::1:5432 (IPv6 Loopback) Node.js 17+ resolves localhost to IPv6 ::1 first, while Postgres/Redis is bound only to IPv4 127.0.0.1 (Runsite) nc -zv 127.0.0.1 5432 vs. nc -zv ::1 5432 Use explicit IPv4 127.0.0.1 in local dev and the Docker service name in Compose (Runsite)
Restarting (1) immediately after docker compose up Bare depends_on starts the app container before PostgreSQL finishes initializing its TCP socket (DEV Guide) docker inspect my-app --format='{{.State.ExitCode}}' Add a pg_isready healthcheck with condition: service_healthy (DEV Guide)
Exited (137) or Exited (0) 137 = Linux kernel OOM killer sent SIGKILL; 0 = entrypoint script finished and exited cleanly (DEV Guide) docker inspect my-app --format='OOM={{.State.OOMKilled}}' Raise memory limit or run the server process in the foreground (DEV Guide)

2. Step-by-Step Repair Walkthrough

Step 1: Freeze the Restart Loop & Inspect the Exit State

You cannot run docker exec against a container that restarts every two seconds. Disable the restart policy first, inspect the exit code, and pull the last 40 lines of stderr (DEV Community):

ssh deploy@vps — Container Crash & Exit Code Inspection STEP 1 TERMINAL CAPTURE
# 1. Stop Docker from endlessly restarting the container while debugging
$ docker update --restart=no api-server-1

# 2. Check the numeric exit code (0 = clean exit, 1 = crash, 137 = OOM kill)
$ docker inspect api-server-1 --format='ExitCode={{.State.ExitCode}} OOMKilled={{.State.OOMKilled}}'
ExitCode=1 OOMKilled=false

# 3. Extract the exact connection failure line
$ docker logs api-server-1 --tail 40 2>&1 | grep -iE "error|econnrefused|fatal"
Error: connect ECONNREFUSED 127.0.0.1:5432 at TCPConnectWrap.afterConnect

Step 2: Wire Docker Service Hostnames & service_healthy in docker-compose.yml

Replace 127.0.0.1 with your Compose service names (db and cache) and require PostgreSQL to pass pg_isready before the application container boots (Runsite; DEV Community):

services:
  app:
    build: .
    restart: unless-stopped
    environment:
      REDIS_URL: redis://cache:6379
      DATABASE_URL: postgresql://app_user:strong_password@db:5432/production_db
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_started

  cache:
    image: redis:7-alpine

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: app_user
      POSTGRES_PASSWORD: strong_password
      POSTGRES_DB: production_db
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app_user -d production_db"]
      interval: 2s
      timeout: 5s
      retries: 15

Step 3: Fail Fast on Missing Env Vars & Add Bounded Exponential Backoff

To prevent pg.Pool from silently defaulting to 127.0.0.1 when an environment variable is missing—and to survive brief database restarts—add this startup check (Runsite) and explore our Open-Source SaaS self-hosting guides:

import pg from "pg";

function requireEnv(name) {
  const value = process.env[name];
  if (!value) {
    console.error(`[FATAL] ${name} is unset; refusing to default to 127.0.0.1`);
    process.exit(1);
  }
  return value;
}

const pool = new pg.Pool({ connectionString: requireEnv("DATABASE_URL") });

async function verifyDatabaseConnection(maxAttempts = 6) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await pool.query("SELECT 1");
    } catch (err) {
      if (err.code !== "ECONNREFUSED" || attempt === maxAttempts) throw err;
      const delayMs = Math.min(500 * 2 ** attempt, 8000);
      console.warn(`[WARN] DB socket not ready (${attempt}/${maxAttempts}), retrying in ${delayMs}ms`);
      await new Promise((r) => setTimeout(r, delayMs));
    }
  }
}

await verifyDatabaseConnection();

Related guides: Fix 502 Bad Gateway in Nginx · Cloudflare Tunnel Error 1033 fix · PostgreSQL 'too many clients' fix · Qwen2.5-Coder vs DeepSeek-V3 benchmark · Free AI API rate limits compared

Browse every guide on the site in our HTML sitemap.

Estimate your API spend with our Free LLM API Quota & Cost Calculator.

Search This Blog

Powered by Blogger.

Blog Archive