PyMongo: pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s
PyMongo couldn't find a usable MongoDB server within the selection timeout.
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refusedpymongo.errors.ServerSelectionTimeoutError: No servers found yetServerSelectionTimeoutError: SSL handshake failedpymongo.errors.ConfigurationError: The "dnspython" module must be installed to use mongodb+srv:// URIspymongo ServerSelectionTimeoutError Timeout: 30s Meaning
Server down, wrong host/port, firewall/Atlas IP list, DNS/SRV failure, or TLS problems. The message lists each host with its error. pip install "pymongo[srv]" is needed for mongodb+srv:// on older versions (dnspython). Lower serverSelectionTimeoutMS while debugging.
Common causes
- mongod not running or wrong host
- Atlas IP not allowed
- Missing dnspython for SRV URIs
- TLS/CA problems (certifi)
- Docker networking
⚡ Quick fix
- Check the host/port with
nc -vz - Install
pymongo[srv]andcertifi - Whitelist your IP in Atlas
Detailed fix by platform
Python
MongoClient(uri, serverSelectionTimeoutMS=5000).admin.command("ping")
How to diagnose
- Error — Per-host reason?
- SRV — dnspython present?
- Allowlist — IP added?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
- BSONObj size is invalid / exceeds maximum document size (16MB) MongoServerError: BSONObj size: 17825792 (0x1100000) is invalid. Size must be between 0 and 16793600(16MB)
- MongoDB Atlas: connection timed out — IP not whitelisted MongoServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted
- MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017 MongoDB: MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
Most viewed in MongoDB
- Document failed validation MongoDB: MongoServerError: Document failed validation (code 121)
- bad auth : Authentication failed MongoDB: MongoServerError: bad auth : Authentication failed (code 8000 / 18)
- StrictPopulateError: Cannot populate path because it is not in your schema Mongoose 6+: StrictPopulateError: Cannot populate path `author` because it is not in your schema
Other ways to find it
Where this error sits
Origin: Data. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 5 Nov 2026