Mongo客户端无法在bash脚本中首次尝试连接

时间:2014-10-03 13:08:00

标签: bash mongodb

我正在开发一个用于自动MongoDB服务器安装和用户创建的bash脚本。

#!/bin/bash
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

该脚本在干净的precision64 Vagrant VM上运行。添加Debian / Ubuntu repo以安装最新版本(我们使用的是Ubuntu 12.04 LTS,维护版本是2.0.X),添加服务器启动,在MongoDB配置文件中设置一些变量。然而,简单的东西,最后一行每次都失败

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

我想也许服务器需要一些时间来在重启和客户端连接之间加载数据或其他类型的初始化,所以我尝试在最后两条指令之间放置一个sleep 30:没有用。但是,从脚本中删除mongo执行并手动启动它每次都像魅力一样! .js不是问题所在,我已经测试了它并且它正常工作。

有没有人知道为什么mongo第一次尝试无法连接以及我如何解决这个问题?现在,我将解决这个可怕的(工作)黑客,但我宁愿有一个更清洁,无懈可击的脚本:

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

    if [[ "${RESULT:-null}" == *Failed\ to\ connect* ]]
    then
        sleep 1
    else
        mongo root_creation.js
        break;
    fi
done 

这很难看,但经过1到10次尝试后,它最终会连接并完美地工作。

0 个答案:

没有答案