How to fix MongoServerSelectionError: Server selection timed out after 30000 ms in MongoDB

MongoDBINTERMEDIATEHIGHUpdated Dec 29, 2025· 203 views

The MongoDB driver failed to connect to any server within the default 30-second timeout window. This typically indicates network connectivity issues, DNS resolution problems, or server availability issues that prevent the driver from locating and connecting to a MongoDB instance.

Quick fix

Fixes SERVER_SELECTION_TIMEOUT

# For local MongoDB
mongo --version
mongosh localhost:27017

# For Docker MongoDB
docker ps | grep mongo

# For MongoDB Atlas, check the cluster status in the web interface
  1. Verify MongoDB server is running and accessible
  2. Verify your connection string is correct
  3. Check network connectivity to MongoDB server
  4. For MongoDB Atlas, verify IP whitelist and user credentials
mongodb — error
# For local MongoDB
mongo --version
mongosh localhost:27017
# For Docker MongoDB
docker ps | grep mongo
# For MongoDB Atlas, check the cluster status in the web interface
MongoServerSelectionError: Server selection timed out after 30000 ms

What this error means

The MongoServerSelectionError occurs when the MongoDB driver's server selection mechanism cannot identify a suitable server to execute an operation within the specified serverSelectionTimeoutMS period (default: 30 seconds). Server selection is the process by which a MongoDB driver chooses the appropriate server for any given read or write operation. The driver continuously monitors all known servers in your MongoDB deployment. If no suitable server can be found after exhausting the 30-second timeout, the driver throws this error instead of waiting indefinitely. This error indicates the driver has connectivity issues, cannot resolve the MongoDB hostname, or the MongoDB server(s) are unavailable or unresponsive.

Typical symptoms

  • Node.js/JavaScript application fails immediately when attempting to connect or query MongoDB
  • Error appears in logs or console output with the exact message referencing "30000 ms" timeout
  • Connection to MongoDB Atlas, self-hosted MongoDB, or Docker-based MongoDB fails
  • Application may work sporadically in some environments but fail consistently in others
  • Error may include topology details like "ReplicaSetNoPrimary" indicating the driver cannot find a primary node

Common causes

  1. Network connectivity is blocked: firewall rules, security groups, or network policies prevent TCP connections to MongoDB port (typically 27017)
  2. DNS resolution failure: the MongoDB hostname cannot be resolved to an IP address
  3. MongoDB server is down or unreachable: the server is not running, crashing, or overloaded
  4. Invalid connection string: incorrect hostname, port, credentials, or missing required parameters
  5. Replica set misconfiguration: the client expects a replica set but the server is not configured as one, or the primary node is unavailable
  6. Connection pool exhaustion: the MongoDB driver exhausted its connection pool and cannot establish new connections
  7. Database server under maintenance or temporarily unavailable

How to fix "MongoServerSelectionError: Server selection timed out after 30000 ms"

1Verify MongoDB server is running and accessible

First, confirm your MongoDB server is actually running and listening on the expected port.

bash
# For local MongoDB
mongo --version
mongosh localhost:27017

# For Docker MongoDB
docker ps | grep mongo

# For MongoDB Atlas, check the cluster status in the web interface

If MongoDB is not running, start it:

bash
# Local on Linux/Mac
mongod

# Local on Windows
"C:\Program Files\MongoDB\Server\bin\mongod.exe"

# Docker
docker run -d -p 27017:27017 mongo
2Verify your connection string is correct

Double-check your MongoDB connection string for typos, correct hostname, and proper formatting.

javascript
// MongoDB Atlas format (recommended)
const uri = "mongodb+srv://username:password@cluster.mongodb.net/database?retryWrites=true&w=majority";

// Local MongoDB format
const uri = "mongodb://localhost:27017/mydb";

// Docker MongoDB
const uri = "mongodb://mongo:27017/mydb";

Common mistakes:
- Using mongo:// instead of mongodb://
- Missing username or password for MongoDB Atlas
- Typos in hostname or database name
- Not URL-encoding special characters in passwords (use encodeURIComponent() for special chars)
- Missing replicaSet=rs0 parameter for replica sets

3Check network connectivity to MongoDB server

Verify network connectivity from your application to the MongoDB server.

bash
# Test DNS resolution
nslookup mongodb.example.com
# or
dig mongodb.example.com

# Test port connectivity
telnet mongodb.example.com 27017
# or (Linux/Mac)
nc -zv mongodb.example.com 27017

# For MongoDB Atlas, verify whitelist IP
# Check MongoDB Atlas dashboard -> Network Access -> IP Whitelist
# Your application's IP must be whitelisted (0.0.0.0/0 allows all IPs, not recommended for production)

If connectivity fails:
- Check firewall rules on both client and server
- Verify security groups (AWS) or network policies (Azure, GCP) allow port 27017
- Confirm MongoDB is listening on 0.0.0.0 not just localhost for remote connections

4For MongoDB Atlas, verify IP whitelist and user credentials

MongoDB Atlas requires explicit IP whitelisting and database users with correct permissions.

1. Navigate to Security → Network Access in the MongoDB Atlas console
2. Add your application's IP address or use 0.0.0.0/0 for testing (restrict to specific IPs in production)
3. Click Security → Database Access and verify:
- Your database user exists
- Password is correct and matches your connection string
- User has appropriate role (at least "readWrite" for the target database)
4. Use the connection string provided by MongoDB Atlas directly

javascript
// Example with credentials
const uri = "mongodb+srv://myuser:mypassword@cluster0.abc123.mongodb.net/mydatabase?retryWrites=true&w=majority";
5Reduce serverSelectionTimeoutMS for faster feedback (optional)

By default, MongoDB waits 30 seconds before timing out. For development, you can reduce this for faster error feedback, but this is NOT recommended for production with replica sets.

javascript
// Mongoose
mongoose.connect(uri, {
  serverSelectionTimeoutMS: 5000, // 5 seconds instead of 30
});

// MongoDB Native Driver
const client = new MongoClient(uri, {
  serverSelectionTimeoutMS: 5000,
});

// Prisma
// Adjust the connection URL
// mongodb://localhost:27017?serverSelectionTimeoutMS=5000

Note: Only reduce this for development or when using a standalone MongoDB server. For replica sets, keep the default 30 seconds to allow time for failovers.

6Check for replica set configuration issues

If using a replica set, ensure proper configuration:

bash
# Connect to MongoDB and check replica set status
mongosh
> rs.status()

# Verify all nodes are healthy (StateStr: PRIMARY, SECONDARY, ARBITER)
# If topology shows "ReplicaSetNoPrimary", the replica set is in an election

For connection strings with replica sets:

javascript
// Must include replicaSet parameter
const uri = "mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=rs0";

// Or for MongoDB Atlas (handles this automatically)
const uri = "mongodb+srv://user:pass@cluster.mongodb.net/db?retryWrites=true&w=majority";
7Review application logs and driver logs for details

Enable MongoDB driver debug logging to see detailed connection attempts:

javascript
// Mongoose
mongoose.set("debug", true);

// MongoDB Native Driver
const { MongoClient, Logger } = require("mongodb");
const logger = new Logger();
logger.setLevel("debug");

// Prisma
// Set environment variable
process.env.DEBUG = "prisma:*";

This will show you:
- Hostnames being attempted
- DNS resolution results
- Network errors
- Connection pool status

Advanced notes

Intermittent timeouts: If you experience occasional timeouts that resolve themselves, consider: Implementing exponential backoff retry logic in your application, scaling up your MongoDB deployment (upgrade tier or add resources), using connection pooling to reuse connections efficiently, or for serverless environments (AWS Lambda, Azure Functions), keeping the MongoDB client in the global scope to reuse connections across invocations.

Kubernetes/Docker deployments: Service names must be DNS-resolvable. In Docker Compose, use service names from docker-compose.yml directly. In Kubernetes, use the service DNS name (e.g., mongodb-service.default.svc.cluster.local).

Public vs. Private endpoints: MongoDB Atlas supports both. Public endpoints are accessible from anywhere but must whitelist your IP. Private endpoints (AWS PrivateLink, Azure Private Link) only work from within your VPC/VNet but are more secure.

Connection string validation: Test your connection string independently before integrating it into your application using mongosh. This isolates connection issues from application code.

Frequently asked questions

What does "SERVER_SELECTION_TIMEOUT" mean?
The MongoServerSelectionError occurs when the MongoDB driver's server selection mechanism cannot identify a suitable server to execute an operation within the specified serverSelectionTimeoutMS period (default: 30 seconds). Server selection is the process by which a MongoDB driver chooses the appropriate server for any given read or write operation. The driver continuously monitors all known servers in your MongoDB deployment.
How do I fix "SERVER_SELECTION_TIMEOUT"?
The MongoDB driver failed to connect to any server within the default 30-second timeout window. This typically indicates network connectivity issues, DNS resolution problems, or server availability issues that prevent the driver from locating and connecting to a MongoDB instance.
What causes "SERVER_SELECTION_TIMEOUT"?
Network connectivity is blocked: firewall rules, security groups, or network policies prevent TCP connections to MongoDB port (typically 27017) DNS resolution failure: the MongoDB hostname cannot be resolved to an IP address MongoDB server is down or unreachable: the server is not running, crashing, or overloaded
Is the "SERVER_SELECTION_TIMEOUT" error serious?
Yes. This is a high-severity error that usually blocks work until it is fixed, but the steps above resolve it.

Official resources & further reading