# MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 — why the app cannot reach MongoDB

> MongoServerSelectionError means the driver spent serverSelectionTimeoutMS, 30 seconds by default, looking for a MongoDB server it could use and found none. With 127.0.0.1:27017 in the message, the app is still using a localhost connection string. With querySrv ENOTFOUND, the mongodb+srv DNS lookup failed. With an Atlas cluster and a plain timeout, the IP access list usually blocks the server. Read the real connection string at runtime, allow the address in Atlas, and check the user, authSource and TLS.

Source: https://livops.dev/en/guides/error-mongoserverselectionerror

By Livops team, the people who build and run Livops. Updated 1 December 2026.

The message depends on the driver and on what went wrong. A Node app using the MongoDB driver prints:

```text
MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
```

Mongoose wraps the same error as `MongooseServerSelectionError`[5]. With an Atlas `mongodb+srv://` string you may see one of these instead:

```text
Error: querySrv ENOTFOUND _mongodb._tcp.cluster0.abcde.mongodb.net
MongoServerSelectionError: Server selection timed out after 30000 ms
```

This page explains what server selection is, lists the causes from the most common with the fix for each, shows how to test the connection string outside the app, and says how a MongoDB database is attached on Livops.

## What does the error mean?

Before every operation, the driver has to pick a server to send it to. If it finds none it can use, it keeps trying for `serverSelectionTimeoutMS`, 30000 milliseconds by default[1], and then throws. That includes the first `mongoose.connect()`, which is why a broken connection string fails only after 30 seconds[4].

So `MongoServerSelectionError` is the wrapper. The reason is the part after the colon:

- **`connect ECONNREFUSED <host>:27017`** — the host answered, and nothing was listening on that port[8]. With `127.0.0.1` or `localhost`, the app looked for MongoDB inside its own container.
- **`querySrv ENOTFOUND _mongodb._tcp...`** — the DNS lookup behind a `mongodb+srv://` string failed before any connection was tried.
- **`Server selection timed out after 30000 ms`** — nothing answered at all, or every attempt failed. The error's `reason` property says why; with a wrong password, for example, it contains an `Authentication failed` error[4].

## Causes, most common first

### 1. The connection string still points to localhost

`mongodb://127.0.0.1:27017/app` or `mongodb://localhost:27017/app` written into the code, or used as the fallback when a variable is missing:

```js
const uri = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/app'
```

On your computer that works. After a deploy, `127.0.0.1` is the app's own container, and the error appears. Read the variable and fail loudly when it is missing instead of falling back:

```js
const uri = process.env.MONGODB_URI
if (!uri) throw new Error('MONGODB_URI is not set')
await mongoose.connect(uri)
```

Check the variable's name too: `MONGO_URL`, `MONGODB_URI` and `MONGO_URI` are all common, and the code has to read the one that is actually set. A `.env` file is usually kept out of the repository, so its values never reach the server.

A related local-only case: Mongoose recommends `127.0.0.1` over `localhost` for a local database, because Node.js 18 and later prefer IPv6 and may resolve `localhost` to `::1`, where a MongoDB without IPv6 is not listening[4].

### 2. Atlas does not allow the server's IP address

Atlas accepts client connections only from the entries in the project's IP access list, each a single address or a CIDR range[3]. Your laptop's address is often on the list from setup; the server's address is not. The connection then hangs until the 30 seconds run out. When Mongoose sees this pattern on an Atlas cluster, it replaces the message with "Could not connect to any servers in your MongoDB Atlas cluster" and points to the access list[5].

Fix: in Atlas, open the project's network access settings and add the address the server connects from. Home and office addresses can change over time, so recheck the list if access stops unexpectedly[3].

Adding `0.0.0.0/0` makes the error go away, and MongoDB's docs warn against it: a `/0` entry allows access from anywhere and can expose the deployment to unauthorized access, and Atlas sends an alert email to the project's members when one is added[3]. If there is no fixed address to allow, use a strong password for every database user, or run the database next to the app.

### 3. The SRV lookup fails (querySrv ENOTFOUND)

A `mongodb+srv://` string does not name the servers. The driver queries DNS for an SRV record in the form `_mongodb._tcp.<host>` and connects to the hosts it lists[2]; it also reads a TXT record, which can supply `replicaSet` and `authSource`[2]. The Node driver does this with Node's `dns.resolve` for the SRV type[6], which always queries a DNS server on the network and ignores `/etc/hosts`[7]. Node's DNS error codes then tell you how it failed: `NOTFOUND` (domain name not found), `REFUSED` (the DNS server refused the query), `CONNREFUSED` (could not contact DNS servers) or `TIMEOUT`[7].

Fix, in this order:

1. Copy the connection string again from Atlas. A missing part of the host, such as `cluster0.abcde.mongodb.net` shortened to `cluster0.mongodb.net`, gives `ENOTFOUND`.
2. Check that the record exists from the same machine: `nslookup -type=SRV _mongodb._tcp.cluster0.abcde.mongodb.net`.
3. If the record exists but the app's DNS server cannot answer SRV queries, use the standard format instead: list every host and port the SRV record returned, as `mongodb://host1:27017,host2:27017,host3:27017/`. That format requires all members to be listed[2], and you also have to add what SRV set for you: `tls=true`, because `+srv` turns TLS on automatically[2], and the `replicaSet` and `authSource` values from the TXT record.

### 4. Wrong user, password or authSource

A wrong password reaches the server and is rejected, but Mongoose can still report it as a server selection timeout; the error's `reason` then contains "bad auth Authentication failed"[4]. Two things to check:

- **Special characters in the password.** If the user name or password contains `$ : / ? # [ ] @`, those characters must be percent-encoded: `@` becomes `%40`[2].
- **`authSource`.** The client authenticates against the `authSource` database; without it, against the database in the path of the string; without both, against `admin`[2]. For Atlas SRV strings, `authSource` is set to `admin` in the TXT record[2]. A user created in `admin` and a string ending in `/myapp` with no `authSource` fails on a server that does not get its value from a TXT record: add `?authSource=admin`.

### 5. TLS does not match

`mongodb+srv://` turns TLS on; a standard `mongodb://` string leaves it off unless you set `tls=true`[1]. A server that requires TLS and a client that does not use it, or the reverse, fail during the handshake. Mongoose names this case separately: "Mongoose is connecting with SSL enabled, but the server is not accepting SSL connections"[5]. Use the string your provider gives you as it is, and add TLS options only when the provider asks for them. A certificate error on the client side is a separate problem: [SSL: CERTIFICATE_VERIFY_FAILED](https://livops.dev/en/guides/error-python-ssl-certificate-verify-failed).

### 6. The server is not up, or is not reachable from here

An address copied from a Docker Compose file (`mongodb://mongo:27017`) works only on that Compose network, and a database's internal host name works only inside its own private network. The general case, for PostgreSQL, MySQL and Redis too, is in [ECONNREFUSED: the app cannot reach its database](https://livops.dev/en/guides/error-econnrefused-database).

## How to confirm the fix

Print the host the app will use, without the password:

```sh
node -e 'const u = process.env.MONGODB_URI; console.log(u.replace(/\/\/[^@]*@/, "//***@"))'
```

If it prints `127.0.0.1` or `localhost`, or fails because the variable is empty, the variable is the problem. Then test the same string outside the app, from the same machine, with a short timeout so the answer comes in seconds:

```sh
mongosh "$MONGODB_URI" --eval 'db.runCommand({ ping: 1 })'
```

```js
// node check.mjs
import { MongoClient } from 'mongodb'
const client = new MongoClient(process.env.MONGODB_URI, { serverSelectionTimeoutMS: 5000 })
await client.db().command({ ping: 1 })
console.log('ok')
await client.close()
```

Mongoose takes the same option, `serverSelectionTimeoutMS: 5000`; its docs suggest lowering it for faster feedback only with a standalone server or a serverless runtime, as replica set failover needs the longer wait[4]. In Python, PyMongo raises `ServerSelectionTimeoutError` when no server is available for an operation, after the same 30 seconds by default[9].

## On Livops

- **MongoDB is a database you add to the project.** Under **Databases**, add MongoDB 7 (the default) or 8.0; the version cannot be changed later. It runs in its own container inside the project environment.
- **The connection string is written for you**, to every service in the environment, including ones added later: `MONGO_URL`, plus `MONGODB_URI`, `MONGO_URI`, `MONGODB_URL`, `MONGOHOST`, `MONGOPORT`, `MONGOUSER` and `MONGOPASSWORD`. Read whichever your code already expects, and use it as written.
- **Variables take effect on the next deploy.** After adding the database, deploy again, or restart the service to apply them now.
- **There is no public port and no IP list.** The database is reachable only from services in its project. Your computer reaches it through **Connect from your computer**, which has a **MongoDB Compass** option, and an SSH tunnel signed by your key.
- **A failed start keeps the old version.** If the app exits on this error, the deploy fails as `start_failed`, the app's last lines are on the **Logs** page, and a web app's previous version keeps running.
- **Backups and a read-only login.** MongoDB is backed up every night (7 daily, 4 weekly, 3 monthly copies), and the team owner can create a `readonly` login for a BI tool.

The variables in [Databases](https://livops.dev/en/docs/databases), and failed starts in [The app did not start](https://livops.dev/en/docs/error-start). A database is free at 500 MB, one per team; 1 GB is 9 credits a month. MongoDB gets at least 384 MiB of memory whatever the size.

## Questions

**Why does it take exactly 30 seconds to fail?**

The MongoDB drivers keep trying to find a usable server for serverSelectionTimeoutMS, which is 30000 milliseconds by default, and only then throw. Set serverSelectionTimeoutMS to 5000 while you debug to see the error sooner.

**Why does it work on my machine and not after deploy?**

On your machine MongoDB runs on the same computer, so 127.0.0.1:27017 reaches it. After a deploy the app runs in its own container, where 127.0.0.1 is the container itself and no MongoDB listens there. The app has to read the real connection string from an environment variable.

**Should I allow 0.0.0.0/0 in the Atlas IP access list?**

Only as a last resort. MongoDB's own docs warn that a /0 entry allows access from anywhere and can expose the cluster, and Atlas sends an alert email to the project's users when one is added. Allow the specific addresses your app connects from, and use a strong password for every database user.

**What does querySrv ENOTFOUND _mongodb._tcp mean?**

A mongodb+srv connection string makes the driver ask DNS for the SRV record _mongodb._tcp plus your cluster host. ENOTFOUND means that record was not found: the host name is mistyped or incomplete, or the DNS server the machine uses cannot answer SRV queries.

**Is it the same error in Python?**

Yes. PyMongo raises ServerSelectionTimeoutError when no MongoDB server is available for an operation, after trying for serverSelectionTimeoutMS, 30 seconds by default. The causes and fixes on this page are the same.

**Do I need an IP access list for a Livops MongoDB?**

No. A Livops database has no public port and is reachable only from services in its own project, so there is no list to fill in. Use the MONGO_URL or MONGODB_URI variable Livops writes to the service.

## Sources

1. [MongoDB Node.js Driver — Specify connection options](https://www.mongodb.com/docs/drivers/node/current/connect/connection-options/). Checked 1 December 2026.
2. [MongoDB Manual — Connection string formats](https://www.mongodb.com/docs/manual/reference/connection-string-formats/). Checked 1 December 2026.
3. [MongoDB Atlas — Configure IP access list entries](https://www.mongodb.com/docs/atlas/security/ip-access-list/). Checked 1 December 2026.
4. [Mongoose docs — Connections](https://mongoosejs.com/docs/connections.html). Checked 1 December 2026.
5. [Mongoose source — lib/error/serverSelection.js](https://github.com/Automattic/mongoose/blob/master/lib/error/serverSelection.js). Checked 1 December 2026.
6. [MongoDB Node.js Driver source — src/connection_string.ts](https://github.com/mongodb/node-mongodb-native/blob/main/src/connection_string.ts). Checked 1 December 2026.
7. [Node.js docs — DNS](https://nodejs.org/api/dns.html). Checked 1 December 2026.
8. [Node.js docs — Errors, common system errors](https://nodejs.org/api/errors.html). Checked 1 December 2026.
9. [PyMongo docs — errors](https://pymongo.readthedocs.io/en/stable/api/pymongo/errors.html). Checked 1 December 2026.
