MongoServerSelectionError: the Node.js driver cannot reach any server
MongoServerSelectionError: 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.
Fix it fast
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 270172Match what you see, then jump to its fix
- 1
Selection 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
querySrv ECONNREFUSED _mongodb._tcp... or DNSHostNotFound: Failed to look up serviceThe mongodb+srv hostname does not resolveFix - 3
connect ECONNREFUSED followed by an IPv6 address such as ::1localhost resolves to IPv6 but the server listens on IPv4 onlyFix - 4
The 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
The SRV host cannot be found, and the cluster page in Atlas shows pausedThe Atlas cluster is paused or still provisioningFix
- 1
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.me2Fix
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 above3Verify
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
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.net2Fix
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
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
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 270173Verify
All members answer from the client, and the driver finds a primary.
mongosh "$MONGODB_URI" --eval "db.runCommand({ ping: 1 })"Confirmed by mongodb.com
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 status2Fix
Resume the cluster in Atlas and wait until it is ready.
# Atlas UI: Resume cluster3Verify
The cluster shows as running and the app connects.
mongosh "$MONGODB_URI" --eval "db.runCommand({ ping: 1 })"Confirmed by mongodb.com
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
Databases
Node.js in Docker Compose cannot find mysql2/promise
The app works on the host but fails after docker compose up
mysql2/promise is a path inside the mysql2 package.
2 causes, each with a fixDatabases
Elasticsearch rejects requests with circuit_breaking_exception: Data too large
circuit_breaking_exception with a reason that contains Data too large
A circuit_breaking_exception with 'Data too large' means Elasticsearch refused work to protect a node's JVM heap.
3 causes, each with a fixDatabases
JupyterLab cannot determine its build status without Node.js
Could not determine jupyterlab build status without nodejs
JupyterLab itself runs without Node.js, but source extensions need Node.js to rebuild it.
3 causes, each with a fixDatabases
Mongoose cannot sign in to MongoDB Atlas: bad auth, authentication failed
MongoError: bad auth Authentication failed.
Authentication failed means the server rejected the user in your connection string.
3 causes, each with a fixDatabases
MongoDB says duplicate key, but the value is null
MongoServerError: E11000 duplicate key error
A unique index in MongoDB stores a missing field as null, and only one null entry is allowed.
3 causes, each with a fixDatabases
mongodb-memory-server will not start under Jest or in Docker
NoSystemBinaryFoundError
When mongodb-memory-server fails to start, the real reason is hidden behind a generic message.
4 causes, each with a fix