本文介绍了如何检查mongodb是否已启动并准备接受来自bash脚本的连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash shell脚本,在尝试mongorestore之前,它会执行很多操作.

I have a bash shell script which does a bunch of stuff before trying to mongorestore.

我想确保不仅MongoDB已启动,而且在尝试还原之前它还准备接受连接.

I want to make sure that not only MongoDB is up, but it is also ready to accept connections before i try restore.

现在,我所看到的是,mongo进程已启动,但要准备好接受连接之前,它需要45秒钟以上的时间进行初始设置(设置日志文件等).理想情况下,我想继续循环测试连接,并且只有在能够连接时,我才想运行mongorestore.

Right now, what I am seeing is, mongo process is up but it take 45+ seconds to do the initial setup (setting up journal files etc) before it is ready to accept connections. Ideally I want to keep testing the connection in a loop and only when I am able to connect, I want to run mongorestore.

有人可以告诉我如何在Bash中做到这一点,或向我指出正确的方向吗?

Can someone show me how to do this in Bash or point me in the right direction?

推荐答案

我最近遇到了同样的问题.我决定配置 mongod ,将其所有输出记录到日志文件中,然后在循环中检查日志文件,直到我们看到一些表明mongod准备就绪的输出为止.

I recently had the same problem. I decided to configure mongod to log all it's output to a logfile and then wait in a loop checking the logfile until we see some output that suggests mongod is ready.

这是我们需要等待的示例日志文件输出行:

This is an example logfile output line we need to wait for:

Tue Dec  3 14:25:28.217 [initandlisten] waiting for connections on port 27017

这是我想到的bash脚本:

This is the bash script I came up with:


#!/bin/bash

# Initialize a mongo data folder and logfile
mkdir -p /data/db
touch /var/log/mongodb.log

# Start mongodb with logging
# --logpath    Without this mongod will output all log information to the standard output.
# --logappend  Ensure mongod appends new entries to the end of the logfile. We create it first so that the below tail always finds something
/usr/bin/mongod  --quiet --logpath /var/log/mongodb.log --logappend &

# Wait until mongo logs that it's ready (or timeout after 60s)
COUNTER=0
grep -q 'waiting for connections on port' /var/log/mongodb.log
while [[ $? -ne 0 && $COUNTER -lt 60 ]] ; do
    sleep 2
    let COUNTER+=2
    echo "Waiting for mongo to initialize... ($COUNTER seconds so far)"
    grep -q 'waiting for connections on port' /var/log/mongodb.log
done

# Now we know mongo is ready and can continue with other commands
...

请注意,脚本不会永远等待,它将在60秒后超时-根据您的使用情况,您可能会或可能不希望这样做.

Notice the script will not wait forever, it will timeout after 60s - you may or may not want that depending on your use case.

这篇关于如何检查mongodb是否已启动并准备接受来自bash脚本的连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 16:08