Fix "MongoDB connect ECONNREFUSED 127.0.0.1:27017" Error

Getting the "MongoDB connect ECONNREFUSED 127.0.0.1:27017" error in your Node.js, Python, or Java application? This complete guide shows you how to start MongoDB service and fix connection issues on Windows, macOS, and Linux.

MongoDB Node.js Mongoose Python Java Express

What This Error Looks Like

Node.js / Mongoose Error:
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at NativeConnection.Connection.openUri (node_modules/mongoose/lib/connection.js:800:32)
    at Mongoose.connect (node_modules/mongoose/lib/index.js:379:15)

Caused by:
Error: connect ECONNREFUSED 127.0.0.1:27017
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)
MongoDB Native Driver (Node.js):
MongoServerError: connect ECONNREFUSED 127.0.0.1:27017
    at Connection.onMessage (node_modules/mongodb/lib/cmap/connection.js:207:30)

Error: getaddrinfo ECONNREFUSED 127.0.0.1:27017
Python / PyMongo Error:
pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:27017: [Errno 111] Connection refused

Traceback (most recent call last):
  File "app.py", line 5, in 
    client = MongoClient('mongodb://localhost:27017/')
pymongo.errors.ConnectionFailure: [Errno 111] Connection refused
Java / Spring Boot Error:
com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)

Quick Fix (Choose Your Operating System)

The Problem: MongoDB service is not running on port 27017

  1. Open Command Prompt as Administrator
  2. Start MongoDB: net start MongoDB
  3. Verify: mongosh (should connect)
  4. Test your application again
  1. Open Terminal
  2. Start MongoDB: brew services start mongodb-community
  3. Verify: mongosh (should connect)
  4. Test your application again
  1. Open Terminal
  2. Start MongoDB: sudo systemctl start mongod
  3. Verify: mongosh (should connect)
  4. Test your application again

Complete Troubleshooting Guide

1 Understand the Error

ECONNREFUSED on port 27017 means:

  • MongoDB server is not running (most common - 90% of cases)
  • MongoDB is running on a different port
  • MongoDB is bound to a different IP address (not 127.0.0.1)
  • Firewall is blocking port 27017
  • MongoDB failed to start due to configuration errors
Key Point: Port 27017 is MongoDB's default port. If nothing responds on this port, your application cannot connect.

2 Check if MongoDB is Running

Check MongoDB Service Status

cmd
# Method 1: Using Services GUI
# Press Win + R, type: services.msc
# Look for "MongoDB" service
# Check if Status shows "Running"

# Method 2: Command line
sc query MongoDB

# Method 3: PowerShell
Get-Service MongoDB

# Method 4: Check if port 27017 is listening
netstat -an | findstr :27017

Expected Output if Running:

SERVICE_NAME: MongoDB
STATE       : 4  RUNNING
TCP    0.0.0.0:27017    0.0.0.0:0    LISTENING

Check MongoDB Service Status

bash
# Method 1: Using Homebrew services
brew services list | grep mongodb

# Method 2: Check process
ps aux | grep mongod

# Method 3: Check if port 27017 is listening
lsof -i :27017
# or
netstat -an | grep 27017

# Method 4: Try connecting with mongosh
mongosh

Expected Output if Running:

mongodb-community started username ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist

# Or with lsof:
mongod  12345 user   11u  IPv4 0x... TCP localhost:27017 (LISTEN)

Check MongoDB Service Status

bash
# Method 1: Using systemctl
sudo systemctl status mongod

# Method 2: Check process
ps aux | grep mongod

# Method 3: Check if port 27017 is listening
sudo lsof -i :27017
# or
sudo netstat -tulpn | grep :27017
# or
sudo ss -tulpn | grep :27017

# Method 4: Try connecting with mongosh
mongosh

Expected Output if Running:

● mongod.service - MongoDB Database Server
   Loaded: loaded (/lib/systemd/system/mongod.service; enabled)
   Active: active (running) since Mon 2024-01-15 10:30:00 UTC
     Docs: https://docs.mongodb.org/manual

3 Start MongoDB Service

Start MongoDB on Windows

Method 1: Using Services GUI (Easiest)

  1. Press Win + R, type services.msc, press Enter
  2. Find "MongoDB" in the list
  3. Right-click → "Start"
  4. Optional: Right-click → "Properties" → Set "Startup type" to "Automatic"

Method 2: Command Line

cmd
# Run Command Prompt as Administrator
# Start MongoDB service
net start MongoDB

# Enable auto-start on boot
sc config MongoDB start=auto

Method 3: PowerShell (as Administrator)

powershell
# Start MongoDB
Start-Service MongoDB

# Set to start automatically
Set-Service MongoDB -StartupType Automatic
If MongoDB service doesn't exist: You may need to install MongoDB as a service:
# Navigate to MongoDB bin directory (adjust path to your version)
cd "C:\Program Files\MongoDB\Server\7.0\bin"

# Install as service
mongod.exe --config "C:\Program Files\MongoDB\Server\7.0\bin\mongod.cfg" --install

Start MongoDB on macOS

Method 1: Using Homebrew Services (Recommended)

bash
# Start MongoDB and run at login (persistent)
brew services start mongodb-community

# Or just start once (stops on logout/restart)
brew services run mongodb-community

# Check status
brew services list

Method 2: Manual Start (Foreground)

bash
# Start MongoDB manually (runs in foreground)
mongod --config /opt/homebrew/etc/mongod.conf

# Or with default settings:
mongod --dbpath /opt/homebrew/var/mongodb --logpath /opt/homebrew/var/log/mongodb/mongo.log
Difference between 'start' and 'run':
  • brew services start - Starts now AND auto-starts on boot/login
  • brew services run - Starts now but doesn't persist across reboots
If MongoDB isn't installed via Homebrew:
# Install MongoDB Community Edition
brew tap mongodb/brew
brew install mongodb-community

# Then start it
brew services start mongodb-community

Start MongoDB on Linux

Using systemctl (Ubuntu/Debian/CentOS/RHEL)

bash
# Start MongoDB
sudo systemctl start mongod

# Enable auto-start on boot
sudo systemctl enable mongod

# Check status
sudo systemctl status mongod

# If mongod service doesn't exist, try:
sudo systemctl start mongodb
sudo systemctl enable mongodb

Manual Start (if systemctl not available)

bash
# Start MongoDB manually
sudo mongod --config /etc/mongod.conf

# Or with default settings:
sudo mongod --dbpath /var/lib/mongodb --logpath /var/log/mongodb/mongod.log --fork
Common issue: If you get "Failed to start mongod.service: Unit mongod.service not found"
# MongoDB might not be installed, or service file missing
# Ubuntu/Debian - Install MongoDB
sudo apt-get update
sudo apt-get install -y mongodb-org

# CentOS/RHEL - Install MongoDB
sudo yum install -y mongodb-org

# Create/reload service
sudo systemctl daemon-reload
sudo systemctl start mongod

4 Verify MongoDB is Listening on Port 27017

After starting MongoDB, confirm it's actually listening on port 27017.

bash
# Windows
netstat -an | findstr :27017

# macOS/Linux
lsof -i :27017
# or
netstat -an | grep 27017
# or
ss -tulpn | grep 27017

Expected Output:

# You should see MongoDB listening on 27017:
TCP    0.0.0.0:27017         0.0.0.0:0              LISTENING
TCP    [::]:27017            [::]:0                 LISTENING

# Or with lsof:
mongod  12345 user   11u  IPv4 0x... TCP localhost:27017 (LISTEN)
If you don't see port 27017: MongoDB is configured to use a different port. Check /etc/mongod.conf (Linux/Mac) or C:\Program Files\MongoDB\Server\X.X\bin\mongod.cfg (Windows) for the port setting under net: section.

5 Test MongoDB Connection

Using MongoDB Shell (mongosh)

bash
# Test connection with mongosh
mongosh

# Or specify connection string explicitly
mongosh "mongodb://localhost:27017"

# If successful, you'll see:
# Current Mongosh Log ID:	...
# Connecting to:		mongodb://127.0.0.1:27017/?directConnection=true
# Using MongoDB:		7.0.2
# Using Mongosh:		2.0.1

Test from Your Application

Node.js / Mongoose:

javascript
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydb', {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => console.log('✓ MongoDB connected successfully'))
.catch(err => console.error('✗ MongoDB connection error:', err.message));

Python / PyMongo:

python
from pymongo import MongoClient

try:
    client = MongoClient('mongodb://localhost:27017/')
    # Test connection
    client.admin.command('ping')
    print('✓ MongoDB connected successfully')
except Exception as e:
    print(f'✗ MongoDB connection error: {e}')

6 Check MongoDB Logs for Errors

If MongoDB still won't start, check the logs for error messages.

cmd
# MongoDB log file location (adjust version number):
type "C:\Program Files\MongoDB\Server\7.0\log\mongod.log"

# Or view last 50 lines:
Get-Content "C:\Program Files\MongoDB\Server\7.0\log\mongod.log" -Tail 50
bash
# Homebrew installation log location:
tail -f /opt/homebrew/var/log/mongodb/mongo.log

# Or view with brew services:
brew services info mongodb-community
bash
# View MongoDB logs
sudo tail -f /var/log/mongodb/mongod.log

# Or using journalctl:
sudo journalctl -u mongod -f

Common error messages in logs:

  • "Address already in use" - Another process using port 27017
  • "Data directory not found" - Create data directory or fix permissions
  • "Insufficient permissions" - Fix file permissions on data directory
  • "Unclean shutdown detected" - Run repair: mongod --repair

Common Issues and Solutions

Issue 1: MongoDB Starts but Immediately Stops

Symptoms: Service starts but status shows "stopped" moments later

Causes:

Solutions:

bash
# Check disk space
df -h  # Linux/Mac
wmic logicaldisk get size,freespace,caption  # Windows

# Remove lock file (if exists)
# Linux/Mac:
sudo rm /var/lib/mongodb/mongod.lock
# Windows:
del "C:\data\db\mongod.lock"

# Repair database
mongod --repair --dbpath /var/lib/mongodb  # Linux/Mac
mongod --repair --dbpath "C:\data\db"      # Windows

# Fix permissions (Linux/Mac)
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chmod -R 755 /var/lib/mongodb

Issue 2: MongoDB Running on Different Port

Symptoms: MongoDB is running but your app can't connect to 27017

Solution: Check MongoDB configuration file for custom port

bash
# Linux/Mac configuration file:
cat /etc/mongod.conf

# Windows configuration file:
type "C:\Program Files\MongoDB\Server\7.0\bin\mongod.cfg"

# Look for:
net:
  port: 27017  # If this is different, that's your issue!
  bindIp: 127.0.0.1

If port is different, either:

Issue 3: Firewall Blocking Port 27017

Rare but possible: Firewall rules blocking localhost:27017

bash
# Windows - Allow port 27017
netsh advfirewall firewall add rule name="MongoDB" dir=in action=allow protocol=TCP localport=27017

# Linux (Ubuntu) - Allow port 27017
sudo ufw allow 27017/tcp

# macOS - Check if firewall is blocking
# System Preferences → Security & Privacy → Firewall → Firewall Options
# Allow incoming connections for mongod

Issue 4: Docker MongoDB Container Not Running

If using MongoDB in Docker:

bash
# Check if MongoDB container is running
docker ps | grep mongo

# If not running, start it
docker start mongodb-container

# Or run a new MongoDB container
docker run -d -p 27017:27017 --name mongodb mongo:latest

# Check container logs
docker logs mongodb-container

# Connect to MongoDB in Docker
docker exec -it mongodb-container mongosh

Quick Reference Commands

cheatsheet
MONGODB SERVICE COMMANDS BY OS
==============================

Windows:
  Check:   sc query MongoDB
  Start:   net start MongoDB
  Stop:    net stop MongoDB
  Enable:  sc config MongoDB start=auto

macOS (Homebrew):
  Check:   brew services list | grep mongodb
  Start:   brew services start mongodb-community
  Stop:    brew services stop mongodb-community
  Restart: brew services restart mongodb-community

Linux (systemd):
  Check:   sudo systemctl status mongod
  Start:   sudo systemctl start mongod
  Stop:    sudo systemctl stop mongod
  Enable:  sudo systemctl enable mongod
  Restart: sudo systemctl restart mongod

VERIFY MONGODB
==============
  Port check:     lsof -i :27017 (Mac/Linux) | netstat -an | findstr :27017 (Win)
  Test connect:   mongosh
  Connection URL: mongodb://localhost:27017

Still Having Issues?

Debugging checklist:

Visit our Interactive Diagnostic Wizard for personalized help.