🔧 Error Fixes
· 3 min read
Last updated on

MongoDB: Connection Failed — How to Fix It


You start your app and it crashes with:

MongoServerError: connect ECONNREFUSED 127.0.0.1:27017

Or the Mongoose variant:

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017

Your application can’t reach the MongoDB server.

What causes this

ECONNREFUSED means your app tried to open a TCP connection to 127.0.0.1:27017 and nothing was listening there. The connection was actively refused by the operating system.

Common causes:

  • MongoDB isn’t running on your machine
  • MongoDB is running but on a different port or interface
  • Your connection string points to localhost but MongoDB is in a Docker container or remote server
  • A firewall is blocking port 27017
  • MongoDB crashed or failed to start due to data directory issues

Fix 1: Start MongoDB

The most common cause — MongoDB simply isn’t running:

# macOS (Homebrew)
brew services start mongodb-community
brew services list | grep mongo

# Linux (systemd)
sudo systemctl start mongod
sudo systemctl status mongod

# Linux (older init systems)
sudo service mongod start

Check if it’s actually listening:

sudo lsof -i :27017
# or
ss -tlnp | grep 27017

If nothing shows up, MongoDB isn’t running or it’s on a different port.

Fix 2: Check your connection string

Make sure the connection string matches your actual MongoDB setup:

// ❌ Missing port (works sometimes, but be explicit)
mongoose.connect('mongodb://localhost/mydb');

// ✅ Explicit port
mongoose.connect('mongodb://localhost:27017/mydb');

// ✅ MongoDB Atlas (cloud)
mongoose.connect('mongodb+srv://<user>:<password>@cluster0.abc123.mongodb.net/mydb');

If you’re using MongoDB Atlas or a remote server, you shouldn’t be connecting to localhost at all. Check your environment variables:

const uri = process.env.MONGODB_URI || 'mongodb://localhost:27017/mydb';
mongoose.connect(uri);

Fix 3: Fix Docker networking

If MongoDB runs in Docker but your app runs on the host (or vice versa), localhost won’t work:

# Start MongoDB in Docker with port mapping
docker run -d -p 27017:27017 --name mongo mongo:7

If both your app and MongoDB are in Docker Compose:

services:
  app:
    build: .
    environment:
      - MONGODB_URI=mongodb://mongo:27017/mydb
    depends_on:
      - mongo
  mongo:
    image: mongo:7
    ports:
      - "27017:27017"

Inside Docker Compose, use the service name (mongo) as the hostname — not localhost.

Fix 4: Check MongoDB’s bind address

By default, MongoDB only listens on 127.0.0.1. If you need to connect from another machine or container, check the config:

# Find the config file
cat /etc/mongod.conf | grep bindIp
# /etc/mongod.conf
net:
  port: 27017
  bindIp: 127.0.0.1  # Change to 0.0.0.0 to allow remote connections

After changing, restart MongoDB:

sudo systemctl restart mongod

Only bind to 0.0.0.0 if you have proper authentication and firewall rules in place.

Fix 5: Check data directory permissions

MongoDB might fail to start silently if it can’t access its data directory:

# Check MongoDB logs
sudo cat /var/log/mongodb/mongod.log | tail -20

# Check data directory permissions
ls -la /var/lib/mongodb/
# Should be owned by mongodb:mongodb

# Fix permissions if needed
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo systemctl restart mongod

How to prevent it

  • Use environment variables for connection strings — never hardcode localhost in production code
  • Add a health check or retry logic to your app’s MongoDB connection so it handles temporary unavailability
  • In Docker Compose, use depends_on with a health check to ensure MongoDB is ready before your app starts
  • Monitor MongoDB with systemctl enable mongod so it starts automatically on boot
  • Keep MongoDB logs accessible and check them first when connections fail — the server-side error is usually more informative than the client-side one