I need help crafting a crontable entry that will make sure the MongoDB service (daemon) is running on a particular port and if it is not, start it. I want to set this up so that if MongoDB crashes, it is automatically restarted. I'd like to have the check occur every five minutes. I have done this for other server processes but those services automatically exit if they find the port they want to bind to is already in use. My concern as a MongoDB newbie is that I'll end up starting yet another instance of MongoDB every five minutes instead of making sure only one instance is loaded. For example, here is my crontable entry for a chatbot service I keep running:

0,5,10,15,20,25,30,35,40,45,50,55 * * * * cd /home/[username]/ChatScript; ./LinuxChatscript32 2>/home/[username]/cronserver.log 

How can I create something similar for MongoDB?

*/5 * * * * /bin/bash -c 'if ! pgrep mongod; then /usr/sbin/service mongodb start; fi'
  • 1
    If I change "pgrep mongod" to "pgrep mongod 27017", will that work for specific ports? I may decide to have more than one Mongo instance running. Note, I'm aware that I'd have to change the port number for each Mongod instance I've configured when crafting/replicating that cron table entry. – Robert Oschler Jul 4 '13 at 13:28
  • @RobertOschler Actually, I don't know the exact mongodb command line. You can figure this out yourself by running ps -o cmd ax | grep mongod. Copy the full mongodb command line returned by that command and use this in crontab: pgrep -f "<full-command-line>". – Eric Carvalho Jul 4 '13 at 13:38

Take a look at supervisor.

It's supposed to do exactly that.


For anyone who stumbles upon this now, I have found Monit to be most useful for this. https://mmonit.com/ it can monitor the port and restart if necessary as well as monitor ram/cpu usage.

The reason I would suggest this is because, in my experience, mongodb can appear to be online with the process still running, but not responding due to high cpu usage or running out of ram.

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.