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).

  1. Check the host in the message matches the MONGODB_URI you expect for this environment.
  2. Test reachability from the same machine: nc -vz <host> 27017 (Atlas SRV hosts resolve to several servers).
  3. On MongoDB Atlas, add the app server's outbound IP to Network Access.
  4. For SSL handshake errors, upgrade certifi and pass tlsCAFile=certifi.where().
  5. Lower serverSelectionTimeoutMS (for example 5000) so failures show up quickly instead of after 30 seconds.
python
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 request

Why 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.

Plans from $29/moSee what your agent readsSee the setupCancel any time from the billing portal

Related errors

References: PyMongo docs: errors (ServerSelectionTimeoutError), MongoDB Atlas docs: configure IP access list