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.
By Livops team, the people who build and run LivopsUpdated
The message depends on the driver and on what went wrong. A Node app using the MongoDB driver prints:
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:
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]. With127.0.0.1orlocalhost, the app looked for MongoDB inside its own container.querySrv ENOTFOUND _mongodb._tcp...— the DNS lookup behind amongodb+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’sreasonproperty says why; with a wrong password, for example, it contains anAuthentication failederror[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:
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:
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:
- Copy the connection string again from Atlas. A missing part of the host, such as
cluster0.abcde.mongodb.netshortened tocluster0.mongodb.net, givesENOTFOUND. - Check that the record exists from the same machine:
nslookup -type=SRV _mongodb._tcp.cluster0.abcde.mongodb.net. - 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+srvturns TLS on automatically[2], and thereplicaSetandauthSourcevalues 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 theauthSourcedatabase; without it, against the database in the path of the string; without both, againstadmin[2]. For Atlas SRV strings,authSourceis set toadminin the TXT record[2]. A user created inadminand a string ending in/myappwith noauthSourcefails 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.
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.
How to confirm the fix
Print the host the app will use, without the password:
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:
mongosh "$MONGODB_URI" --eval 'db.runCommand({ ping: 1 })'
// 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, plusMONGODB_URI,MONGO_URI,MONGODB_URL,MONGOHOST,MONGOPORT,MONGOUSERandMONGOPASSWORD. 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
readonlylogin for a BI tool.
The variables in Databases, and failed starts in The app did not 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
- MongoDB Node.js Driver — Specify connection options (mongodb.com). Checked .
- MongoDB Manual — Connection string formats (mongodb.com). Checked .
- MongoDB Atlas — Configure IP access list entries (mongodb.com). Checked .
- Mongoose docs — Connections (mongoosejs.com). Checked .
- Mongoose source — lib/error/serverSelection.js (github.com). Checked .
- MongoDB Node.js Driver source — src/connection_string.ts (github.com). Checked .
- Node.js docs — DNS (nodejs.org). Checked .
- Node.js docs — Errors, common system errors (nodejs.org). Checked .
- PyMongo docs — errors (pymongo.readthedocs.io). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy with MongoDBRelated
- ECONNREFUSED / Connection refused: why the app cannot reach its database after deployNothing was listening at the address your app tried. When the address is 127.0.0.1 or localhost, the app never read the database's real address: DATABASE_URL is not set, is not read, or is read during a build that has no database. Attach the database, read DATABASE_URL (or REDIS_URL, MYSQL_URL) at runtime, run migrations before the start rather than in the build, and keep the connection pool under the server's limit.
- Prisma P1001: Can't reach database server at … — how to fix itPrisma tried the host and port in your connection URL and nothing answered there. After a deploy that is almost always a URL that says localhost, a database that is not attached to the project, or prisma migrate deploy running in a build that has no database. Read the host in the message first: it tells you which.
- [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate in Python: how to fix itssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate means Python could not build a chain from the server's certificate to a root it trusts. In requests, httpx, aiohttp and urllib the usual causes are a missing or outdated CA bundle, a python.org install on macOS that never ran Install Certificates.command, a corporate proxy that re-signs HTTPS, or a server that does not send its intermediate certificate. Fix the trust store; do not turn verification off.
- App not listening on $PORT: why the health check failed after deployThe platform started your app, tried the port it gave it, and nothing answered in time. Almost always the app listens on its own fixed port instead of the PORT variable, listens on localhost (127.0.0.1) instead of 0.0.0.0, or crashed or was still starting when the check gave up. Listen on 0.0.0.0 and the port in PORT, and it passes.
- Express.js hosting in 2026: the options comparedAn Express app in production needs one long-running Node process that listens on process.env.PORT on every interface, trusts exactly the proxy in front of it, exits cleanly on SIGTERM, and keeps sessions and data in a database rather than in memory. On Livops an Express repository deploys from a push for 39 credits a month (39,000 so'm). Here is how Render, Railway, Fly.io, Vercel and a VPS with pm2 compare.
- Node.js hosting in 2026: how to deploy an Express appA Node.js server in production needs one long-running process that listens on the port it is given, restarts when it crashes and exits cleanly on SIGTERM. On Livops you push a repository with package.json and it runs as a web app for 39 credits a month (39,000 so'm). Here is what Node needs, and how a VPS, Render, Railway, Fly.io, DigitalOcean and Heroku compare.
- Error: connect ECONNREFUSED 127.0.0.1:6379 — why the app cannot reach Redis after deployECONNREFUSED 127.0.0.1:6379, or Error 111 connecting to localhost:6379 in Python, means nothing was listening where the app looked for Redis. After a deploy that is almost always the app's own container: REDIS_URL is not set, is not read, or the client was created without it and fell back to localhost. Pass the URL to the client, attach a Redis the app can reach, and keep redis:// and rediss:// as the provider gives them.