MongoDB "Server selection timed out" connection timeout in CI
The MongoDB driver tried to select a server and none became reachable before the server-selection timeout (30s by default). In CI this is usually a wrong host, an unready container, or a single-node replica set that never elected a primary.
What this error means
The driver fails with "MongoServerSelectionError: Server selection timed out after 30000 ms" or "connection timed out", listing the addresses it tried.
MongoServerSelectionError: Server selection timed out after 30000 ms
topology: { type: 'Unknown', servers: { '127.0.0.1:27017': { type: 'Unknown' } } }Common causes
The host or port is wrong or unreachable
Connecting to the container name instead of the mapped 127.0.0.1:27017, or a port that is not published, leaves the driver with no reachable node.
A replica set never elected a primary
If you start mongod with --replSet but never run rs.initiate(), the set has no primary, so writeable server selection times out.
How to fix it
Connect to the published address
Use the mapped port on localhost and confirm the port is published.
env:
MONGODB_URI: mongodb://127.0.0.1:27017/app_testInitiate a single-node replica set
If you need transactions, initiate the set so a primary is elected before tests run.
mongosh --host 127.0.0.1:27017 --eval 'rs.initiate()'How to prevent it
- Wait for the container healthcheck before the driver connects.
- Initiate
--replSetinstances so a primary exists. - Connect to the published localhost port, not the container hostname.