[SOLVED] How to Fix 'connect ECONNREFUSED 127.0.0.1:27017' in MongoDB
The exception MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 or MongoNetworkError: failed to connect to server [localhost:27017] in Node.js / Express applications indicates that the client attempted a TCP socket connection on port 27017, but no active MongoDB daemon was listening.
Quick Diagnostics
sudo systemctl start mongod && sudo systemctl enable mongodsudo chown -R mongodb:mongodb /var/lib/mongodb and run repairThe exception MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 or MongoNetworkError: failed to connect to server [localhost:27017] in Node.js / Express applications indicates that the client attempted a TCP socket connection on port 27017, but no active MongoDB daemon was listening.
Step-by-Step Solution
-
1
Step 1: Inspect and Start MongoDB Daemon
Check whether the
mongodsystemd unit is healthy:BASH# Inspect daemon status sudo systemctl status mongod # Start service if inactive sudo systemctl start mongod # Enable persistent boot start sudo systemctl enable mongod -
2
Step 2: Fix Data and Log Directory Permissions
Abrupt system halts can leave database storage directories locked or misattributed:
BASH# Restore ownership to system 'mongodb' user sudo chown -R mongodb:mongodb /var/lib/mongodb sudo chown -R mongodb:mongodb /var/log/mongodb # Set standard directory access sudo chmod -R 755 /var/lib/mongodb -
3
Step 3: Validate Network Binding in mongod.conf
Inspect your master configuration file (
/etc/mongod.conf):YAML# /etc/mongod.conf net: port: 27017 bindIp: 127.0.0.1 # Localhost bindingRestart daemon to apply configuration changes:
BASHsudo systemctl restart mongod -
4
Step 4: Verify Local Database Connectivity
Confirm socket responsiveness via the official Mongo shell:
BASHmongosh "mongodb://127.0.0.1:27017"
❓ Frequently Asked Questions (FAQ)
What does status=14/EXIT_FAILURE mean on mongod startup?
Exit code 14 indicates permission failures or stale mongod.lock files. Run sudo mongod --repair --dbpath /var/lib/mongodb and restart the service.
Why does my Docker app fail connecting to 127.0.0.1?
Inside a container, 127.0.0.1 references the container loopback interface. Reference your MongoDB container by service name defined in docker-compose.yml.
Prevention Advice
Recommended security practices:
- Never expose 0.0.0.0 without active authentication: Exposing port 27017 to public networks without
security.authorization: enabledrisks automated database scraping and ransomware encryption. - Monitor disk capacity: MongoDB halts the WiredTiger engine if free storage falls below 100MB.