[MongoDB] Error: failed to connect to [localhost:27017]
When developing a web application with Node.js (Express) + MongoDB structure, I encountered the following error when starting the app (node-dev app.js).
The web app couldn’t connect to mongo at all. I could connect from CLI though.
[ERROR] 21:57:58 Error
Error: failed to connect to [localhost:27017]
at null. (/Users/your_username/git/com/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:540:74)
at EventEmitter.emit (events.js:106:17)
at null. (/Users/your_username/git/com/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15)
at EventEmitter.emit (events.js:98:17)
at Socket. (/Users/your_username/git/com/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:478:10)
at Socket.EventEmitter.emit (events.js:95:17)
at net.js:830:16
at process._tickCallback (node.js:415:13)
After trying various solutions without success, I ended up reinstalling mongodb.
% brew uninstall mongodb
Uninstalling /usr/local/Cellar/mongodb/2.4.8...
% brew install mongodb
If installation doesn’t take much time, it would be fine, but mongodb takes several minutes to compile, so reinstalling every time is a bit painful.
By the way, here’s what I tried troubleshooting:
I tried deleting mongod.lock and restarting, and also tried —repair, but nothing worked.
% ps aux | grep mongo
your_username 572 0.0 0.4 2721360 36264 ?? S 10:00PM 0:00.61 /usr/local/opt/mongodb/mongod run --config /usr/local/etc/mongod.conf
your_username 896 0.0 0.0 2432784 600 s003 S+ 10:04PM 0:00.00 grep mongo
% launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
% ps aux | grep mongo
your_username 982 0.0 0.0 2432784 608 s003 S+ 10:07PM 0:00.00 grep mongo
% rm /usr/local/var/mongodb/mongod.lock
% launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
% ps aux | grep mongo
your_username 1060 0.0 0.0 2432784 604 s003 S+ 10:11PM 0:00.00 grep mongo
your_username 1052 0.0 0.4 2712144 34696 ?? S 10:11PM 0:00.06 /usr/local/opt/mongodb/mongod run --config /usr/local/etc/mongod.conf
If anyone knows the solution, I would appreciate your help.
Still unresolved, and when this symptom occurs, I’m dealing with it by “System Shutdown” → “Startup” (restart doesn’t work).
Successfully resolved! (2013/12/17)
The cause was that the application was trying to connect to localhost:27017, but there was nothing written in /etc/hosts, so it couldn’t connect to localhost.
It could be resolved by either changing the mongodb connection settings in the application to 127.0.0.1, or fixing /etc/hosts.
I was using a Mac app called “hoster” to manage the hosts file, but this might have been causing trouble, so I dunked it into the trash.
That’s all from the Gemba.