What's Actually Happening

MongoDB connection timeouts occur when clients cannot establish connections to MongoDB server. This happens due to server overload, network issues, firewall blocks, or misconfigured connection settings.

The Error You'll See

Connection timeout:

```bash $ mongosh "mongodb://mongodb-server:27017"

MongoNetworkTimeoutError: connection timeout Server selection timeout: 30000 ms exceeded ```

Application error:

bash
MongoTimeoutError: Server selection timed out after 30000 ms
Available servers: []
Topology description: { type: 'Unknown', servers: {} }

Node.js driver error:

bash
MongoNetworkError: connection 1 to mongodb-server:27017 timed out

Why This Happens

  1. 1.MongoDB not running - Server process stopped
  2. 2.Network unreachable - Host not accessible from client
  3. 3.Firewall blocking - Port 27017 blocked
  4. 4.Server overloaded - Too many connections
  5. 5.Wrong connection string - Invalid host/port
  6. 6.DNS resolution failure - Hostname not resolving

Step 1: Check MongoDB Server Status

```bash # Check MongoDB process running ps aux | grep mongod

# Check MongoDB systemd status systemctl status mongod

# Check MongoDB port listening netstat -tlnp | grep 27017

# Connect locally on server mongosh

# Check server status mongosh --eval "db.serverStatus().connections"

# Get MongoDB info mongosh --eval "db.adminCommand('replSetGetStatus')" # For replica sets

# Check MongoDB logs tail -100 /var/log/mongodb/mongod.log ```

Step 2: Test Network Connectivity

```bash # Ping MongoDB server ping mongodb-server -c 5

# Check port connectivity nc -zv mongodb-server 27017

# Using telnet telnet mongodb-server 27017

# Test with timeout nc -w 5 -zv mongodb-server 27017

# Check route traceroute mongodb-server

# Check DNS resolution nslookup mongodb-server dig mongodb-server

# From application server (client machine) # Run network tests from where the timeout occurs ```

Step 3: Check Firewall Rules

```bash # Check iptables iptables -L -n -v | grep 27017

# Allow MongoDB port iptables -I INPUT -p tcp --dport 27017 -j ACCEPT

# Allow from specific client IP iptables -I INPUT -s 192.168.1.100 -p tcp --dport 27017 -j ACCEPT

# Using ufw ufw status ufw allow 27017/tcp ufw allow from 192.168.1.100 to any port 27017

# Using firewalld firewall-cmd --list-all firewall-cmd --add-port=27017/tcp --permanent firewall-cmd --reload

# Check cloud firewall rules # AWS: Security Groups # Azure: Network Security Groups # GCP: Firewall Rules ```

Step 4: Check MongoDB Connection Limits

```bash # Check current connections mongosh --eval "db.serverStatus().connections" # Output: { current: 100, available: 81900, totalCreated: 500 }

# Current connections exceeding limit causes timeouts

# Check max connections from config mongosh --eval "db.adminCommand({getParameter: 1, maxConn: 1})"

# Default max connections is 100,000

# Check ulimit on server mongosh --eval "db.serverStatus().connections.limit"

# If ulimit too low, increase it # Edit /etc/security/limits.conf: mongod soft nofile 64000 mongod hard nofile 64000

# Or systemd service file # /etc/systemd/system/mongod.service [Service] LimitNOFILE=64000

# Restart MongoDB systemctl restart mongod ```

Step 5: Increase Client Timeout Settings

```javascript // Node.js driver - increase timeout const { MongoClient } = require('mongodb');

const client = new MongoClient('mongodb://mongodb-server:27017', { serverSelectionTimeoutMS: 30000, // 30 seconds (default 30s) connectTimeoutMS: 30000, // Connection timeout (default 30s) socketTimeoutMS: 0, // No socket timeout (default 0) heartbeatFrequencyMS: 10000, // Heartbeat interval maxPoolSize: 100 // Connection pool size });

await client.connect(); ```

```python # Python pymongo - configure timeout from pymongo import MongoClient

client = MongoClient( 'mongodb://mongodb-server:27017', serverSelectionTimeoutMS=30000, connectTimeoutMS=30000, socketTimeoutMS=None, maxPoolSize=100 )

# Test connection client.admin.command('ping') ```

```java // Java driver - connection settings MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString("mongodb://mongodb-server:27017")) .applyToServerSettings(builder -> builder .serverSelectionTimeout(30, TimeUnit.SECONDS)) .applyToSocketSettings(builder -> builder .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS)) .applyToConnectionPoolSettings(builder -> builder .maxSize(100) .maxWaitTime(10, TimeUnit.SECONDS)) .build();

MongoClient client = MongoClient.create(settings); ```

Step 6: Use Connection Pooling

```javascript // Node.js - connection pool configuration const client = new MongoClient('mongodb://mongodb-server:27017', { maxPoolSize: 50, // Maximum pool size minPoolSize: 10, // Minimum pool size maxIdleTimeMS: 30000, // Close idle connections after 30s waitQueueTimeoutMS: 5000 // Wait time for connection from pool });

// Pool creates and manages connections efficiently // Reuses connections instead of creating new ones each time ```

```python # Python pymongo - pool settings client = MongoClient( 'mongodb://mongodb-server:27017', maxPoolSize=50, minPoolSize=10, maxIdleTimeMS=30000, waitQueueTimeoutMS=5000 )

# Use same client instance throughout application # Don't create new MongoClient for each operation ```

Step 7: Check for Replica Set Issues

```bash # For replica sets, connection timeout may indicate member issues

# Check replica set status mongosh --eval "rs.status()"

# Check if members are reachable mongosh --eval "rs.status().members.forEach(m => print(m.name + ': ' + m.stateStr))"

# Check replica set config mongosh --eval "rs.conf().members"

# If primary is unreachable: # - Driver cannot find primary for writes # - Set serverSelectionTimeoutMS higher

# Connection string for replica set mongodb://mongo1:27017,mongo2:27017,mongo3:27017/?replicaSet=myReplicaSet

# Driver tries all members before timing out

# Check member sync status mongosh --eval "rs.printReplicationInfo()" mongosh --eval "rs.printSlaveReplicationInfo()" ```

Step 8: Fix Connection String Issues

```bash # Validate connection string format

# WRONG: Invalid format mongodb://mongodb-server // Missing port mongodb://mongodb-server:27018 // Wrong port mongodb://mongodb-server:27017/database?authSource=wrongDB // Wrong auth database

# CORRECT: Proper connection string mongodb://mongodb-server:27017 mongodb://mongodb-server:27017/myDatabase mongodb://mongodb-server:27017/myDatabase?authSource=admin

# For authentication mongodb://user:password@mongodb-server:27017/myDatabase?authSource=admin

# For replica set mongodb://mongo1:27017,mongo2:27017,mongo3:27017/?replicaSet=myReplicaSet

# For TLS/SSL mongodb://mongodb-server:27017/?tls=true

# Test connection string mongosh "mongodb://mongodb-server:27017" ```

Step 9: Check Server Resource Load

```bash # Check MongoDB server load mongosh --eval "db.serverStatus().metrics.operation"

# Check memory usage mongosh --eval "db.serverStatus().memory"

# Check current operations mongosh --eval "db.currentOp()"

# Check slow queries blocking connections mongosh --eval "db.currentOp({secs_running: {$gt: 10}})"

# Kill long-running operations mongosh --eval "db.killOp(opId)"

# Check CPU on server top -p $(pgrep mongod)

# Check disk I/O iostat -x 1 5

# If overloaded: # - Scale horizontally (sharding) # - Add replica set members # - Optimize queries # - Increase server resources ```

Step 10: Monitor and Alert

```bash # Create monitoring script cat << 'EOF' > /usr/local/bin/check_mongodb_connections.sh #!/bin/bash CURRENT=$(mongosh --quiet --eval "db.serverStatus().connections.current") AVAILABLE=$(mongosh --quiet --eval "db.serverStatus().connections.available")

if [ "$CURRENT" -gt 1000 ]; then echo "ALERT: MongoDB connections high: $CURRENT" mongosh --eval "db.currentOp()" | mail -s "MongoDB Connection Alert" admin@company.com fi EOF

chmod +x /usr/local/bin/check_mongodb_connections.sh

# Add to cron echo "*/1 * * * * root /usr/local/bin/check_mongodb_connections.sh" > /etc/cron.d/mongodb-monitor

# MongoDB monitoring commands mongosh --eval "db.serverStatus().connections" mongosh --eval "db.serverStatus().network" mongosh --eval "db.serverStatus().metrics.commands" ```

Connection Timeout Diagnostic Checklist

CheckCommandExpected
MongoDB runningsystemctl status mongodactive (running)
Port reachablenc -zv host 27017succeeded
Firewall allowsiptables -L27017 ACCEPT
Connections availableserverStatus()available > 0
DNS resolvesnslookup hostIP returned

Verify the Fix

```bash # After addressing timeout causes

# 1. Test connection mongosh "mongodb://mongodb-server:27017" # Should connect without timeout

# 2. Ping database mongosh --eval "db.adminCommand('ping')" # Should return { ok: 1 }

# 3. Check server status mongosh --eval "db.serverStatus().host"

# 4. Test from application # Application should connect successfully

# 5. Monitor connections mongosh --eval "db.serverStatus().connections" # Connections should be stable

# 6. Check network latency ping mongodb-server -c 100 # Low latency, no packet loss ```

  • [Fix MongoDB Authentication Failed](/articles/fix-mongodb-authentication-failed)
  • [Fix MongoDB Query Timeout](/articles/fix-mongodb-query-timeout)
  • [Fix MongoDB Replica Set Sync Lag](/articles/fix-mongodb-replica-set-sync-lag)