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.
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)
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
pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:27017: [Errno 111] Connection refused Traceback (most recent call last): File "app.py", line 5, inclient = MongoClient('mongodb://localhost:27017/') pymongo.errors.ConnectionFailure: [Errno 111] Connection refused
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)
The Problem: MongoDB service is not running on port 27017
net start MongoDBmongosh (should connect)brew services start mongodb-communitymongosh (should connect)sudo systemctl start mongodmongosh (should connect)ECONNREFUSED on port 27017 means:
# 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
# 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)
# 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
Method 1: Using Services GUI (Easiest)
Win + R, type services.msc, press EnterMethod 2: Command Line
# 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)
# Start MongoDB Start-Service MongoDB # Set to start automatically Set-Service MongoDB -StartupType Automatic
# 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
Method 1: Using Homebrew Services (Recommended)
# 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)
# 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
brew services start - Starts now AND auto-starts on boot/loginbrew services run - Starts now but doesn't persist across reboots# Install MongoDB Community Edition brew tap mongodb/brew brew install mongodb-community # Then start it brew services start mongodb-community
Using systemctl (Ubuntu/Debian/CentOS/RHEL)
# 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)
# 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
# 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
After starting MongoDB, confirm it's actually listening on port 27017.
# 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)
/etc/mongod.conf (Linux/Mac) or C:\Program Files\MongoDB\Server\X.X\bin\mongod.cfg (Windows) for the port setting under net: section.
# 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
Node.js / Mongoose:
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:
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}')
If MongoDB still won't start, check the logs for error messages.
# 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
# Homebrew installation log location: tail -f /opt/homebrew/var/log/mongodb/mongo.log # Or view with brew services: brew services info mongodb-community
# View MongoDB logs sudo tail -f /var/log/mongodb/mongod.log # Or using journalctl: sudo journalctl -u mongod -f
Common error messages in logs:
mongod --repairSymptoms: Service starts but status shows "stopped" moments later
Causes:
Solutions:
# 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
Symptoms: MongoDB is running but your app can't connect to 27017
Solution: Check MongoDB configuration file for custom port
# 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:
Rare but possible: Firewall rules blocking localhost:27017
# 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
If using MongoDB in Docker:
# 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
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
Debugging checklist:
mongodb://localhost:27017Visit our Interactive Diagnostic Wizard for personalized help.