pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s
Python · updated 2026-11-04
Raised by the first operation that needs a server, after PyMongo spends serverSelectionTimeoutMS (30 seconds by default) trying to reach one. The text after the error names the host and the underlying reason (connection refused, SSL handshake failed, timed out).
Traceback (most recent call last):
File "/app/sync.py", line 12, in <module>
users = list(db.users.find({"active": True}))
...
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 6553..., topology_type: Unknown, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]>Quick fix
Read the host and reason in the message. Connection refused on localhost usually means the wrong connection string for this environment (or Docker networking). For Atlas, add the app's IP to the network access list. SSL errors usually mean an outdated CA bundle (pip install -U certifi).
- Check the host in the message matches the MONGODB_URI you expect for this environment.
- Test reachability from the same machine: nc -vz <host> 27017 (Atlas SRV hosts resolve to several servers).
- On MongoDB Atlas, add the app server's outbound IP to Network Access.
- For SSL handshake errors, upgrade certifi and pass tlsCAFile=certifi.where().
- Lower serverSelectionTimeoutMS (for example 5000) so failures show up quickly instead of after 30 seconds.
import os
import certifi
from pymongo import MongoClient
client = MongoClient(
os.environ["MONGODB_URI"],
serverSelectionTimeoutMS=5000, # fail in 5 s, not 30
tlsCAFile=certifi.where(), # fixes most Atlas SSL handshake errors
)
client.admin.command("ping") # check at startup, not on the first requestWhy it happens
The wrong connection string
A localhost URI deployed to a server, or a missing environment variable falling back to the default, points PyMongo at a database that is not there.
IP allowlist on MongoDB Atlas
Atlas rejects connections from addresses not in Network Access; new servers, serverless functions and changed IPs time out.
SSL and certificate problems
An outdated CA bundle or old OpenSSL fails the TLS handshake with Atlas, which surfaces as this timeout with an SSL reason.
Docker networking
Inside a container, localhost is the container itself; use the Mongo service name in the URI.
Other fixes
- Ping the server at startup so a bad URI fails the deploy instead of the first user request.
- For replica sets, make sure the hostnames the servers advertise are resolvable from the app.
Same error, other wording
- pymongo.errors.ServerSelectionTimeoutError: cluster0-shard-00-00.abcde.mongodb.net:27017: SSL handshake failed
- pymongo.errors.ServerSelectionTimeoutError: No replica set members found yet, Timeout: 30s
- pymongo.errors.ConnectionFailure: localhost:27017: [Errno 111] Connection refused
Let your coding agent catch the next one
Runheed records this error in production with the stack trace, the breadcrumbs before it and the agent session that shipped the code, and serves it to Claude Code, Cursor or any MCP client. With it connected, you can ask:
> Find the pymongo ServerSelectionTimeoutError exceptions in production, show me the host and reason in each one, and fix the connection string, the Atlas network access list or the CA bundle accordingly.
Related errors
- [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer...
- psycopg2.OperationalError: server closed the connection unexpectedly
- requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.example.com'...
References: PyMongo docs: errors (ServerSelectionTimeoutError), MongoDB Atlas docs: configure IP access list