Restarting MongoDB automatically if it crashes

Solution 1:

I found the answer myself: the simplest way to achieve that is to add the following two lines at the end of the upstart script installed by MongoDB (/etc/init/mongodb.conf):

respawn
respawn limit 10 90

This will try to restart the process if it terminates, and stop if it crashes more than 10 times in 90 seconds.

Solution 2:

Building on the accepted answer (and since I do not have enough rep to comment on it)

Respawn is NOT a mongo configuration parameter, it is for the upstart service configuration file.

respawn
respawn limit 10 90

Digital Ocean has a nice tutorial for using upstart and systemd (newer). https://www.digitalocean.com/community/tutorials/how-to-configure-a-linux-service-to-start-automatically-after-a-crash-or-reboot-part-1-practical-examples

Solution 3:

I think you want something like Monit or God here to automatically restart services when they stop/crash. Your description of the crash itself would suggest the OOM Killer, which can be avoided by configuring some swap space on the host.