🔧 Error Fixes
· 1 min read

MongoDB ServerSelectionTimeoutError — How to Fix It


pymongo.errors.ServerSelectionTimeoutError: connection closed
MongoServerSelectionError: connection timed out

Your application can’t reach the MongoDB server within the timeout period.

Fix 1: Check Connection String

# ❌ Common mistakes
mongodb://localhost:27017  # Wrong if using Atlas
mongodb+srv://user:pass@cluster.mongodb.net  # Wrong password

# ✅ Copy the exact string from MongoDB Atlas
# Atlas → Connect → Drivers → Copy connection string

Fix 2: IP Whitelist (Atlas)

# ❌ Your IP isn't whitelisted
# ✅ Atlas → Network Access → Add IP Address
# For development: 0.0.0.0/0 (allow all)
# For production: add your server's IP

Fix 3: MongoDB Not Running (Local)

# Check if mongod is running
sudo systemctl status mongod

# Start it
sudo systemctl start mongod

# Check logs
sudo tail -20 /var/log/mongodb/mongod.log

Fix 4: DNS Resolution (SRV Records)

# ❌ mongodb+srv:// requires DNS SRV lookup
# Some networks block SRV lookups

# ✅ Use standard connection string instead
mongodb://user:pass@shard1.mongodb.net:27017,shard2.mongodb.net:27017/mydb?ssl=true&replicaSet=atlas-xxx

Fix 5: Increase Timeout

# Python
client = MongoClient(uri, serverSelectionTimeoutMS=10000)  # 10 seconds

# Node.js
mongoose.connect(uri, { serverSelectionTimeoutMS: 10000 });

Fix 6: Firewall / VPN

# Check if port 27017 is reachable
nc -zv cluster.mongodb.net 27017

# If behind a VPN, MongoDB Atlas might be blocked
# Try disconnecting VPN or adding Atlas IPs to allowlist

Related: What is Redis