I've been trying to use Mongoid with Rails on Ubuntu. Mongodb was working fine for me with rails app 3.0 to 3.2.

Today suddenly, I am getting an error:

/home/pravinmishra/.rvm/gems/ruby-1.9.2-p318/gems/mongo-1.5.2/lib/mongo/connection.rb:413:in `connect': Failed to connect to a master node at localhost:27017 (Mongo::ConnectionFailure)

Many times I faced this issue, and the commands below worked for me:

sudo rm /var/lib/mongodb/mongod.lock
sudo -u mongodb mongod -f /etc/mongodb.conf --repair
sudo start mongodb
sudo status mongodb

When I'm connecting from Ubuntu terminal using mongo then I get this error:

MongoDB shell version: 2.0.1 connecting to: test Mon Jul 9 22:47:06 Error: couldn't connect to server shell/mongo.js:84 exception: connect failed

Any suggestion would be appreciated.

  • check the log and find out why it isn't starting – Mike Jul 9 '12 at 18:11
  • you mean /var/log/mongodb/mongodb.log? – Pravin Mishra Jul 9 '12 at 18:21
  • yes i do. tail it as you start mongo.. should tell you why it's not starting. – Mike Jul 9 '12 at 18:24
  • Mon Jul 9 23:21:58 [initandlisten] exception in initAndListen: 12596 old lock file, terminating – Pravin Mishra Jul 9 '12 at 18:31
  • edit your post with more then a single line from the logs.. post the whole part of the log from start to end of a start up – Mike Jul 9 '12 at 18:37

Maybe your mongodb instance quited unexpectedly and you have stale locks and the database in inconsistent state.

As you already guessed start mongoDB with the --repair flag, but after that you need to restart it again without it.

Also make sure that all the processes are really terminated or you won't be able to bind the server on the same port. I would recommend to execute netstat -tulnp and double check if there is nothing listening on the 27017 port.


Based on your comment, about the old lock file error, you either have a mongod already running and you are trying to connect to the wrong port, or you have a case of an unclean shutdown of a previously running mongod process and you need to remove the lock file and restart (possibly with repair depending on the nature of the unclean shutdown).

If this happens again, definitely make sure you are running with journaling enabled (default in 2.0), then repair should not be necessary.


You may not be able to connect to the default localhost:27017 as the previous instance must have terminated incorrectly due to errors or exceptions or locks. Please try killing the previous processes and then running it again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.