database
connection_error
ai_generated
true
pymongo.errors.ServerSelectionTimeoutError: connection refused, Timeout: 30s
ID: database/mongodb-connection-failed
91%Fix Rate
93%Confidence
58Evidence
2023-06-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7 | active | — | — | — |
Root Cause
MongoDB client cannot connect to any server in the connection string within the server selection timeout. Typically caused by mongod not running, wrong host/port, firewall blocking port 27017, or replica set misconfiguration.
genericWorkarounds
-
92% success Start the MongoDB service and verify it is listening
Run: sudo systemctl start mongod. Verify: sudo systemctl status mongod. Check it is listening: ss -tlnp | grep 27017. Check mongod.log for startup errors. If using a replica set, ensure the replica set is initialized with rs.initiate().
-
88% success Fix the connection string and network configuration
Verify the connection string format: mongodb://host:27017/dbname. Check bindIp in mongod.conf (set to 0.0.0.0 for remote access or specific IPs). Check firewall: sudo ufw allow 27017. For Atlas, ensure IP whitelist includes the client IP.
Dead Ends
Common approaches that don't work:
-
Increasing serverSelectionTimeoutMS to very large values
90% fail
If the server is not running or unreachable, waiting longer will not help. This only delays the error and makes the application appear to hang instead of failing fast.
-
Reinstalling the MongoDB driver (pymongo/mongoose) to fix connection issues
95% fail
Connection refused is a network-level error. The driver correctly reports that the server is unreachable. Reinstalling the driver changes nothing about server availability.
Error Chain
Preceded by:
Frequently confused with: