Node.js cannot connect to MongoDB: ECONNREFUSED on port 27017
MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]Short answer
ECONNREFUSED means nothing accepted the connection at that address and port. In Docker Compose the usual cause is using localhost inside the app container, where it points at the app itself; use the Mongo service name. Other causes: mongod starting later than the app, localhost resolving to IPv6, or a firewall.
Fix it fast
1Find out which cause you have
Check whether anything listens on 27017 where the app is running. On the host use ss; inside a container, ask Compose which services are up and read the database log.
sudo ss -ltn | grep 27017 docker compose ps docker compose logs --tail 30 mongo2Match what you see, then jump to its fix
- 1
ECONNREFUSED 127.0.0.1:27017 in a Compose project while the mongo container is healthyThe app container uses localhost, which is the app container itselfFix - 2
Fails right after docker compose up, then works if you restart only the appThe app starts before MongoDB is ready to accept connectionsFix - 3
The error shows ::1:27017, or works with 127.0.0.1 and fails with localhostlocalhost resolves to IPv6 but MongoDB listens on IPv4Fix - 4
Nothing listens on 27017 in the first-step output, or it listens only on the machine that is not yoursmongod is not running, or a firewall blocks the portFix
- 1
What does the error look like?
MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017MongoServerSelectionError: connect ECONNREFUSED ::1:27017
Cause 1 of 4
The app container uses localhost, which is the app container itself
1Check
Each container has its own network namespace. Containers on one Compose network reach each other by service name, on the container port, so a connection string with localhost never leaves the app container.
docker compose exec app printenv MONGO_URL
grep -n "mongo" docker-compose.yml compose.yaml 2>/dev/null2Fix
Use the service name as host and the container port. The host port in a ports mapping only matters for connections from outside the network.
services:
app:
environment:
MONGO_URL: mongodb://mongo:27017/myapp
mongo:
image: mongo:83Verify
Restart the stack and watch the app log connect.
docker compose up -d
docker compose logs --tail 20 appConfirmed by docs.docker.com
Cause 2 of 4
The app starts before MongoDB is ready to accept connections
1Check
Compose by default waits until a dependency container is running, not until it is ready.
docker compose logs mongo | grep -i "waiting for connections"2Fix
Give mongo a healthcheck and make the app wait for it to be healthy.
services:
mongo:
image: mongo:8
healthcheck:
test: ["CMD", "mongosh", "--quiet", "--eval", "db.runCommand({ ping: 1 }).ok"]
interval: 10s
retries: 5
app:
depends_on:
mongo:
condition: service_healthy3Verify
Bring the stack up from stopped; the app connects on the first try.
docker compose down && docker compose up -d
docker compose logs --tail 20 appConfirmed by docs.docker.com
Cause 3 of 4
localhost resolves to IPv6 but MongoDB listens on IPv4
1Check
In Node.js 17 and later, the resolver can return an IPv6 address first. If mongod is on IPv4 only, the client is refused.
node -e "require('dns').lookup('localhost', {all:true}, (e,a)=>console.log(a))"2Fix
Write 127.0.0.1 in the connection string, or ask the driver for IPv4 with family: 4.
await mongoose.connect('mongodb://127.0.0.1:27017/myapp');
// or: mongoose.connect(uri, { family: 4 })3Verify
The connect call resolves and queries run.
node -e "require('mongoose').connect('mongodb://127.0.0.1:27017/myapp').then(()=>{console.log('ok');process.exit(0)})"Confirmed by mongodb.com
Cause 4 of 4
mongod is not running, or a firewall blocks the port
1Check
MongoDB uses 27017 by default. A stopped service has no listener, and a firewall between the app and database host drops or refuses the traffic.
sudo systemctl status mongod
sudo ss -ltn | grep 270172Fix
Start the service. If the database is on another host, open 27017 only to the app's address, and give it a fail-fast timeout so a bad address shows up quickly.
sudo systemctl start mongod
# in the app
mongoose.connect(uri, { serverSelectionTimeoutMS: 5000 });3Verify
The port is now listening and the app connects.
sudo ss -ltn | grep 27017Confirmed by mongoosejs.com
How do I stop it coming back?
- Read the MongoDB host from an environment variable and set it to the service name in Compose, 127.0.0.1 on a laptop.
- Use a healthcheck plus service_healthy for every database your app needs at boot.
- Wrap the first mongoose.connect in try/catch and exit with a clear message, because the driver does not retry the first connection for you.
- Open a database port to the network only for the hosts that need it.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- Dispatch ProA real-time logistics platform: Flutter apps, Spring Boot services and a Kafka event pipeline on AWS.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
Related fixes
Back end
Node.js in Docker Compose cannot reach MySQL on 127.0.0.1:3306
Error: connect ECONNREFUSED 127.0.0.1:3306
Inside a container, 127.0.0.1 is that container, not MySQL.
3 causes, each with a fixBack end
A Docker build or container says npm: not found
npm: command not found
A container only has the programs its image holds.
3 causes, each with a fixBack end
ECS task stops with exec format error on start
exec /usr/local/bin/docker-entrypoint.sh: exec format error
The container's binary was built for another CPU than the task runs on.
2 causes, each with a fixBack end
Kong Gateway returns 502 'An invalid response was received from the upstream server'
upstream sent too big header while reading response header from upstream
Kong returns 502 when it cannot get a valid HTTP response from the upstream.
4 causes, each with a fixBack end
NestJS watch mode does not restart after I save a file
Changes show on the host but not in the running container
Watch mode only sees files that exist inside the process that runs it.
3 causes, each with a fixBack end
Node.js request fails with getaddrinfo EAI_AGAIN
errno: -3001, code: 'EAI_AGAIN', syscall: 'getaddrinfo'
EAI_AGAIN means the system resolver asked a name server and got a temporary failure back.
3 causes, each with a fix