Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Databases and Redis

MongoServerSelectionError: the Node.js driver cannot reach any server

ErrorMongoServerSelectionError: connect ECONNREFUSED <IPv6 address>:<port>

Short answer

MongoServerSelectionError means the driver could not find a usable server before its timeout, so no node answered or no primary was found. Check four things in order: the Atlas IP access list, whether the SRV hostname resolves, whether localhost resolves to IPv6, and whether every replica set member hostname is reachable from the client.

  • Applies to MongoDB Node.js driver 6, Mongoose 8, Node.js 22, MongoDB Atlas
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Test the network path before the code. Resolve the SRV name from your connection string, then open a TCP connection to the port.

    dig SRV _mongodb._tcp.cluster0.example.mongodb.net
    nc -zv cluster0-shard-00-00.example.mongodb.net 27017
  2. 2Match what you see, then jump to its fix

    1. 1Selection times out although the connection string and credentials are right, and the same string works from another networkYour IP address is not in the Atlas IP access listFix
    2. 2querySrv ECONNREFUSED _mongodb._tcp... or DNSHostNotFound: Failed to look up serviceThe mongodb+srv hostname does not resolveFix
    3. 3connect ECONNREFUSED followed by an IPv6 address such as ::1localhost resolves to IPv6 but the server listens on IPv4 onlyFix
    4. 4The driver connects to the seed host, then fails to find a primary, or one member never answersReplica set members are not reachable under the hostnames in the configFix
    5. 5The SRV host cannot be found, and the cluster page in Atlas shows pausedThe Atlas cluster is paused or still provisioningFix

What does the error look like?

  • MongoServerSelectionError: connect ECONNREFUSED <IPv6 address>:<port>
  • Error: querySrv ECONNREFUSED _mongodb._tcp.<SRV Record>
  • DNSHostNotFound: Failed to look up service "<MongoDB service name>"

Cause 1 of 5

Your IP address is not in the Atlas IP access list

1Check

Atlas only accepts clients from the IP addresses and CIDR ranges in the project's access list. A home connection, a new server or a container host that changed its address is no longer allowed.

curl -s https://ifconfig.me

2Fix

Add the address that the app connects from to the project's IP access list in Atlas, under Network Access.

# Atlas UI: Network Access > Add IP Address > enter the address printed above

3Verify

Run the app again, or connect with the same string from that machine.

mongosh "$MONGODB_URI" --eval "db.runCommand({ ping: 1 })"

Confirmed by mongodb.com

Did this fix it?

Cause 2 of 5

The mongodb+srv hostname does not resolve

1Check

mongodb+srv URIs need DNS SRV lookups. Some routers and ISPs block them. The dig command in the first step shows an empty answer when they fail.

dig SRV _mongodb._tcp.cluster0.example.mongodb.net

2Fix

Switch the machine or network to a public DNS resolver that supports SRV records, or use the standard mongodb:// connection string, which Atlas offers when the SRV option is turned off in the Connect dialog.

# Atlas Connect dialog: turn off the SRV connection string option and copy the
# mongodb:// string; it lists every host and port.
MONGODB_URI="mongodb://USER:PASSWORD@host1:27017,host2:27017,host3:27017/?replicaSet=SET_NAME&authSource=admin"

3Verify

The dig command returns records, or the standard string connects.

mongosh "$MONGODB_URI" --eval "db.runCommand({ ping: 1 })"

Confirmed by mongodb.com

Did this fix it?

Cause 3 of 5

localhost resolves to IPv6 but the server listens on IPv4 only

1Check

On Node.js 17 and later the resolver prefers IPv6. A local mongod bound to IPv4 refuses the IPv6 attempt.

node -e "require('dns').lookup('localhost',(e,a,f)=>console.log(a,f))"

2Fix

Force IPv4 in the client options, or use 127.0.0.1 in the connection string.

const { MongoClient } = require('mongodb');
const client = new MongoClient(uri, { family: 4 });

3Verify

The connection succeeds without changing the server.

node -e "require('mongodb').MongoClient.connect(process.env.MONGODB_URI,{family:4}).then(c=>{console.log('ok');return c.close()})"

Confirmed by mongodb.com

Did this fix it?

Cause 4 of 5

Replica set members are not reachable under the hostnames in the config

1Check

The driver discovers the other members from the replica set configuration and then connects to those hostnames. The connection string hostnames must match the configuration, and every host must be reachable from the client.

echo "$MONGODB_URI" | sed -E 's#^mongodb://[^@]*@##; s#/.*##' | tr ',' '\n'

2Fix

Make each listed hostname resolvable and open on its port from the client machine, or change the member hostnames in the replica set configuration.

# from the client machine, for every host the command above prints
nc -zv host1.internal 27017

3Verify

All members answer from the client, and the driver finds a primary.

mongosh "$MONGODB_URI" --eval "db.runCommand({ ping: 1 })"

Confirmed by mongodb.com

Did this fix it?

Cause 5 of 5

The Atlas cluster is paused or still provisioning

1Check

A paused cluster has no running hosts to find. Free clusters pause automatically after 30 days with no connections.

# Atlas UI: Database > Clusters, and look at the cluster status

2Fix

Resume the cluster in Atlas and wait until it is ready.

# Atlas UI: Resume cluster

3Verify

The cluster shows as running and the app connects.

mongosh "$MONGODB_URI" --eval "db.runCommand({ ping: 1 })"

Confirmed by mongodb.com

Did this fix it?

How do I stop it coming back?

  • Keep the app's outbound IP address fixed, or use private networking, so the access list stays correct.
  • Test a new environment with mongosh and the real connection string before deploying the app.
  • Set connectTimeoutMS to a value higher than your slowest member's latency, so a distant member is not dropped.
  • Never open port 27017 to the whole internet to make a test pass.

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:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.