I'm working on a bash script for automatic MongoDB server installation and user creation.

apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | tee /etc/apt/sources.list.d/mongodb.list
apt-get update
apt-get install -y mongodb-org
update-rc.d mongod defaults
sed -i 's/^auth = true/#auth = true/g' /etc/mongod.conf
sed -i 's/^#noauth = true/noauth = true/g' /etc/mongod.conf
service mongod restart
mongo user_creation.js

The script is run on a clean precise64 Vagrant VM. Add the Debian/Ubuntu repo to install the latest version (we're on Ubuntu 12.04 LTS, MongoDB version 2.6.4), add server to startup, set some variables in the MongoDB config file. Simple stuff really, however, the last line fails each and every time.

MongoDB shell version: 2.6.4 connecting to: test 2014-10-03T12:34.:56.000+0000 
warning: Failed to connect to, reason: errno:111 Connection refused
2014-10-03T12:34.:56.000+0000 Error: couldn't connect to server 
(, connection attempt failed at src/mongo/shell/mongo.js:146
exception: connect failed

I thought maybe the server needed some time to load data or some other kind of initialization between its restart and the client connection so I tried putting a sleep 30 between the last two instructions : didn't work. However, removing the mongo execution from the script and starting it manually works like a charm every time! The .js is not the problem here, I've tested it and it's working alright.

Does anyone have any idea why the mongo cannot connect on its first try and how I could fix this? For now, I'll settle with this terrible (working) hack, but I'd rather have a cleaner, hackless script:

while :
    RESULT=`mongo --eval "1;"`
    echo $RESULT

    if [[ "${RESULT:-null}" == *Failed\ to\ connect* ]]
        sleep 1
        mongo root_creation.js

It's ugly but after 1 to 10 tries, it ends up connecting and working perfectly.

  • Quick question: you mention using version 2.0.X but then post a 2.6.4 shell output, and that is the current version from the MongoDB repository (you should not use the packages from the Ubuntu repository as they are frozen on the older version). Can you clarify which version is actually being used for anyone trying to reproduce this? – Adam C Oct 7 '14 at 8:59
  • Yes, you're right, it's not terribly clear. I'm using the 2.6.4 version of both the MongoDB server and client, using the official 10gen repo. I'll edit my question for clarity. – SolarBear Oct 7 '14 at 12:32
  • 3
    Can you post your mongod.log file? This is likely a timing issue, which the log file could help confirm. This could be time spent preallocating journal or local database files for example. – James Wahlin Oct 7 '14 at 12:52

Your Answer

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

Browse other questions tagged or ask your own question.