Tuesday 14 January 2020

Auto Startup/Stop MongoDB with shell scripting


With MongoDB packages, We can easily start and stop mongodb with service command but we face auto start and stop issue while we install MongoDB with tarball file.
To automate start/stop mongo activity we can use shell scripting. 
Below is example of shell script which we can use for MongoDB auto startup and stop process.

First, You need to create scripts for MongoDB startup and Stop. This is how mine looks like:



  • vi /data/users/mongodb/scripts/mongo_start.sh

        #!/bin/bash
        # script to start the MongoDB
        . ~/.bash_profile
        # start the database
        mongod -f /data/users/mongodb/config/mongod.conf
        exit 0

  • vi /data/users/mongodb/scripts/mongo_stop.sh
     #!/bin/bash
     # script to stop the MongoDB
     . ~/.bash_profile
    # stop the database
    ps -ef | grep mongod | grep -v grep | awk '{print $2}' | xargs kill
    exit 0

You see that inside the scripts, we are calling the .bash_profile file of the user. This is needed to set the MONGO_HOME environment variable.

Next, give execute rights to the scripts:

  • chmod u+x mongo_stop.sh mongo_start.sh
You could now test these scripts to see if they correctly shut down and start up your Mongo database.

We will now create a wrapper script that can be used to schedule as a service.

With user root, create a file called “mongo” under /etc/init.d.

  • vi /etc/init.d/mongo
      #!/bin/bash
      # chkconfig: 345 99 10
      # description: mongo auto start-stop script.
      # Set MONGO_OWNER to the user id of the owner of the
     
      MONGO_OWNER=mongodb
      RETVAL=0

      case "$1" in
             'start')        
      su - $MONGO_OWNER -c "/data/users/mongodb/scripts/mongo_start.sh"
        touch /var/lock/subsys/mongo
        ;;
    'stop')
        su - $MONGO_OWNER -c "/data/users/mongodb/scripts/mongo_stop.sh"
        rm -f /var/lock/subsys/mongo
        ;;
    *)
        echo $"Usage: $0 {start|stop}"
        RETVAL=1
     esac
     exit $RETVAL

Next, provide required permission

  • chmod 750 /etc/init.d/mongo
To create a service of this script, run the following command
  • chkconfig --add mongo
Next, check the script by running “service mongo stop” or “service mongo start” from the command line.

After this, it’s time for the final test: reboot your server and check if your Mongo database is automatically started after the reboot.

Good luck! :-)






No comments:

Post a Comment