MongoError: failed to connect to server in Node.js

In this Node.js Tutorial, we shall learn to fix MongoError: failed to connect to server by investigating into the scenarios that could trigger this error.

This connection error usually means that the Node.js application could not open a network connection to the MongoDB server at the host and port given in the connection string. In local development, the most common causes are that the MongoDB service is not running, the port is different from 27017, the hostname is wrong, or the application is running inside Docker and trying to connect to the wrong localhost.

To fix Node.js MongoError: failed to connect to server, follow the two checkpoints

  1. Make sure MongoDB Service is up and running.
  2. The URL you provide to the MongoClient.connect() method should be correct.

After these two checks, also verify authentication, firewall rules, Docker networking, and the difference between localhost and 127.0.0.1 if the problem continues.

Common reasons for MongoError failed to connect to server

Error conditionWhat it usually meansWhat to check first
Connection refused on 127.0.0.1:27017No MongoDB process is listening on the local MongoDB port.Start the mongod service and check the port.
Server selection timed outThe driver could not find a reachable MongoDB server before timeout.Check host, port, DNS, firewall, and replica set options.
Authentication failedThe server is reachable, but the username, password, database, or auth source is wrong.Check credentials and the authentication database.
ECONNREFUSED localhost:27017 inside DockerThe app container is connecting to itself, not to the MongoDB container.Use the MongoDB service name from Docker Compose.
Connection works in shell but not in Node.jsThe Node.js connection string or driver options may not match the working shell connection.Copy the same host, port, database, and credentials into the app configuration.

How to Verify if MongoDB Service is up and running

Starting the Mongo Shell should verify this.

If your MongoDB Service is not up, you would get an Error in the Terminal as below.

Terminal – Starting Mongo Shell

arjun@tutorialkart:~/workspace/nodejs/mongodb$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
2017-10-30T14:32:21.476+0530 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2017-10-30T14:32:21.477+0530 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:237:13
@(connect):1:6
exception: connect failed

Start your MongoDB Service with the command below :

   sudo service mongod start

There should be no error reported when you start Mongo Daemon, mongod.

And when the Service is up, and Mongo Shell is started,

Terminal – Mongo Shell

arjun@tutorialkart:~/workspace/nodejs/mongodb$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9

On many current MongoDB installations, the shell command is mongosh instead of mongo. You can use either command depending on the tools installed on your system.

</>
Copy
mongosh "mongodb://127.0.0.1:27017"

If MongoDB is installed as a systemd service on Linux, you can also check the service status before starting your Node.js application.

</>
Copy
sudo systemctl status mongod
sudo systemctl start mongod

If you are on macOS and installed MongoDB with Homebrew services, check the service from Homebrew instead of using systemctl.

</>
Copy
brew services list
brew services start mongodb-community

How to make sure that the MongoDB URL is correct?

When we start Mongo Shell, MongoDB logs the URL to Terminal, similar to something like below :

connecting to: mongodb://127.0.0.1:27017

mongodb://127.0.0.1:27017 is the base url.

Make sure that you are providing the same base URL (same IP and Port) in your Node.js Application.

node-js-mongodb-connection.js

</>
Copy
// URL at which MongoDB service is running
var url = "mongodb://localhost:27017";

// A Client to MongoDB
var MongoClient = require('mongodb').MongoClient;

// Make a connection to MongoDB Service
MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Connected to MongoDB!");
  db.close();
});

If the MongoDB server runs on the same computer as your Node.js application, mongodb://127.0.0.1:27017 and mongodb://localhost:27017 often point to the same local server. If name resolution or IPv6 settings create confusion, test with 127.0.0.1 explicitly.

</>
Copy
const { MongoClient } = require('mongodb');

const url = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(url);

async function main() {
  try {
    await client.connect();
    console.log('Connected to MongoDB');
  } catch (error) {
    console.error('MongoDB connection failed:', error.message);
  } finally {
    await client.close();
  }
}

main();

The example above uses the newer async/await style. It also prints the error message instead of throwing immediately, which makes the first troubleshooting step easier.

Fixing MongoServerSelectionError in a Node.js MongoDB connection

Some recent versions of the MongoDB Node.js driver may show MongoServerSelectionError instead of the older MongoError: failed to connect to server message. The meaning is similar: the driver tried to find a usable MongoDB server, but it could not select one before the timeout.

Use a small server selection timeout while debugging so the application fails quickly and prints a clear message.

</>
Copy
const { MongoClient } = require('mongodb');

const client = new MongoClient('mongodb://127.0.0.1:27017', {
  serverSelectionTimeoutMS: 5000
});

async function testConnection() {
  try {
    await client.connect();
    await client.db('admin').command({ ping: 1 });
    console.log('MongoDB ping succeeded');
  } catch (error) {
    console.error(error.name + ': ' + error.message);
  } finally {
    await client.close();
  }
}

testConnection();

If the ping fails, the issue is still at the connection layer. Check the MongoDB service, hostname, port, network route, authentication, and whether the server is bound to the interface you are using.

Checking whether MongoDB is listening on port 27017

If MongoDB is running but Node.js still cannot connect, check whether a process is actually listening on port 27017. This helps separate a stopped service from a wrong port or bind address problem.

</>
Copy
ss -ltnp | grep 27017

On systems where ss is not available, use netstat.

</>
Copy
netstat -ltnp | grep 27017

If no output appears, MongoDB may not be listening on that port. Check the MongoDB configuration file for the configured port and bind IP.

tcp   LISTEN 0 128 127.0.0.1:27017 0.0.0.0:*

The sample output above shows MongoDB listening only on 127.0.0.1. That is normally fine for a local Node.js application, but a remote application or another container will not be able to connect to it through an external network address.

Fixing localhost MongoDB connection errors in Docker

A common cause of this error is using mongodb://localhost:27017 from inside a Docker container. Inside the Node.js container, localhost refers to the Node.js container itself, not the MongoDB container.

When using Docker Compose, connect to MongoDB by the service name. For example, if the MongoDB service is named mongo, the application connection string should use mongodb://mongo:27017.

</>
Copy
services:
  app:
    build: .
    environment:
      MONGODB_URI: mongodb://mongo:27017/tutorialkart
    depends_on:
      - mongo

  mongo:
    image: mongo:latest
    ports:
      - "27017:27017"

In the Node.js code, read the connection string from an environment variable so that local, Docker, staging, and production environments can use different MongoDB URLs without changing source code.

</>
Copy
const { MongoClient } = require('mongodb');

const uri = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/tutorialkart';
const client = new MongoClient(uri);

async function connectToMongoDB() {
  await client.connect();
  console.log('Connected using:', uri.replace(/:\/\/.*@/, '://***@'));
}

connectToMongoDB().catch((error) => {
  console.error('MongoDB connection error:', error.message);
  process.exit(1);
});

Fixing MongoDB authentication failed errors in Node.js

If the error says Authentication failed, MongoDB is reachable, but the login details are not accepted. This is different from a network connection refused error.

  • Check that the username and password are correct.
  • Make sure special characters in the password are URL-encoded in the connection string.
  • Check whether the user was created in the database named in authSource.
  • Confirm that the user has permission to access the database used by the Node.js application.
</>
Copy
const uri = 'mongodb://appUser:encodedPassword@127.0.0.1:27017/appdb?authSource=admin';

Do not hard-code real passwords in application files. Store connection strings in environment variables or a secret manager, especially outside local development.

QA checklist for Node.js MongoDB connection troubleshooting

  • MongoDB service is running before the Node.js app starts.
  • The app uses the correct MongoDB host and port.
  • The connection string includes the correct database name if the app expects one.
  • The MongoDB shell can connect using the same host, port, and credentials.
  • Docker apps use the MongoDB service name instead of localhost.
  • Authentication errors are separated from network connection errors.
  • Firewall, bind IP, and cloud network rules allow the app to reach MongoDB.
  • The app logs the error name and message during debugging without printing real passwords.

FAQs on MongoError failed to connect to server in Node.js

Why does Node.js show MongoError failed to connect to server localhost:27017?

It usually means no MongoDB server is listening at localhost on port 27017, or the Node.js process cannot reach it. Start MongoDB, confirm the port, and test the same URL with mongo or mongosh.

What is the difference between MongoError and MongoServerSelectionError?

MongoError is an older general error name used by earlier MongoDB Node.js driver versions. MongoServerSelectionError is commonly seen in newer driver versions when the driver cannot find a reachable MongoDB server before the timeout.

Why does MongoDB connect from terminal but fail from a Node.js app?

The terminal and Node.js app may not be using the same connection string. Compare the host, port, database name, username, password, authSource, and environment variables used by the application.

How do I fix MongoDB localhost connection error inside Docker?

Do not use localhost to reach a separate MongoDB container. Use the Docker Compose service name, such as mongodb://mongo:27017/dbname, from the Node.js container.

Can wrong MongoDB credentials cause failed to connect errors?

Yes, but the message is usually authentication related. If the server is reachable and credentials are wrong, check the username, password, authSource, and database permissions.

Summary: fixing Node.js MongoDB failed to connect errors

In this Node.js MongoDB Tutorial – Node.js MongoError: failed to connect to server, we have learned some of the checkpoints to fix the error.

Start with the simplest checks: confirm that MongoDB is running, confirm the connection URL, and test the same host and port from the shell. If the error still appears, check the driver error name, Docker networking, authentication settings, bind IP, firewall rules, and whether the application is using the expected environment variable for the MongoDB URI.