Introduction
If you have installed MongoDB and you want to monitor , start MongoDB service when it stops.
Prerequisites
- Ubuntu/CentOS with Minimal Installation
- Preinstalled MongoDB
- SSH access with sudo privileges
Step 1: Shell Script to Start MongoDB Service if down
Create the shell file named chkmongo.sh
sudo nano chkmongo.sh
Paste the below scripts into it
#!/bin/bash
########################################################
## Shell Script to Start MongoDB Service if down by FOSSTechNix.com
########################################################
mongod_status=`service mongod status`
echo "${mongod_status}"
if [[ "${mongod_status}" == *"active/running"* ]]
then
echo "MongoDB Service is already running."
else
sudo service mongod start
echo "Start MongoDB Service"
fi
OR
#!/bin/bash
########################################################
## Shell Script to Start MongoDB Service if down by FOSSTechNix.com
########################################################
mongod_status=`sudo systemctl start mongod`
echo "${mongod_status}"
if [[ "${mongod_status}" == *"active/running"* ]]
then
echo "MongoDB Service is already running."
else
sudo systemctl start mongod
echo "Start MongoDB Service"
fi
Before proceeding, note that there are two mechanical requirements to enable shell script execution.
- The script must be “executable”.
- The script must be “findable” for execution.
$ sudo chmod +x /home/chkmongo.sh
OR
$ sudo chmod 0755 /home/chkmongo.sh
Step 2: Schedule cronjob
To set the cronjob follow below command and execute on Linux terminal.
$ sudo su
# crontab -e
Add the below command in the editor to check MongoDB service every 5 Minute.
*/5 * * * /home/chkmongo.sh
Conclusion
In this article, using the shell sript we created file, created shell Shell Script to Start MongoDB Service if down and scheduled cron job to check MongoDB service every 5 minute
Related Articles:
Shell Script for MySQL DataBase Backup
Reference: