If your self-hosted n8n container cannot reach Postgres, Redis, or an API on the host, you will often see ECONNREFUSED. This guide explains why it happens inside Docker and how to fix it with host.docker.internal and extra_hosts.
Container networking is the usual root cause of ECONNREFUSED in n8n Docker setups.
Why localhost inside Docker is not your machine
Every container has its own network namespace. Inside n8n, localhost (or 127.0.0.1) means the container itself, not the laptop or VPS running Docker.
So if Postgres is installed on the host at port 5432, this will fail from n8n:
DB_POSTGRESDB_HOST=localhost
You need a hostname that resolves to the host gateway.
What ECONNREFUSED actually means
ECONNREFUSED means a TCP connection reached an IP/port where nothing accepted it (or a firewall rejected it). In n8n Docker this is usually:
- Wrong host (
localhostinside the container) - Service bound only to
127.0.0.1on the host - Firewall (UFW) blocking Docker bridge traffic
- Containers on isolated networks without a route to each other
The fix: Docker host gateway
On Docker Desktop (macOS/Windows), host.docker.internal often works out of the box.
On Linux, map it explicitly with Compose:
version: "3.8"
services:
n8n:
image: docker.n8n.io/n8nio/n8n:latest
container_name: n8n_production
restart: unless-stopped
ports:
- "5678:5678"
environment:
- GENERIC_TIMEZONE=UTC
- DB_TYPE=postgresdb
- DB_POSTGRESDB_HOST=host.docker.internal
- DB_POSTGRESDB_PORT=5432
- DB_POSTGRESDB_USER=n8n_user
- DB_POSTGRESDB_PASSWORD=your_secure_password
- DB_POSTGRESDB_DATABASE=n8n_database
extra_hosts:
- "host.docker.internal:host-gateway"
volumes:
- n8n_storage:/home/node/.n8n
volumes:
n8n_storage:
In production, prefer an explicit Docker network when both apps are containerized.
Linux notes
host-gatewayis supported on modern Docker Compose.- Ensure Postgres listens on an interface Docker can reach. For host Postgres, bind carefully and restrict with UFW.
macOS and Windows
Docker Desktop injects host.docker.internal. Still set the same env vars so Compose files stay portable.
Prefer a shared Compose network
If Postgres is also a container, do not use host gateway. Put both on one network and use the service name as the DB host.
Common pitfalls
- UFW on Ubuntu can block Docker forwarding.
- IPv6 confusion when apps resolve
localhostto::1. - Volume permission errors that appear before the DB connection.