denny denny - 5 months ago 49
Linux Question

How to run mongodb (extracted from tar.gz) as service in Ubuntu?

For some reason in my area, I'm unable to download and install mongodb normally using

apt-get
from terminal. So I downloaded the
.tar.gz
version from http://docs.mongodb.org/manual/tutorial/install-mongodb-on-linux/

I can start it's
mongod
program. But I want to install mongod as a service that runs at startup in my Ubuntu 14.04. How to do this correctly ?
I tried some init.d script provided by this : https://ewan.im/15/mongodb-initd-script

The only problem is: in 14.04, they removed the
chkconfig
. My experiment to install chkconfig ended up with

Package chkconfig is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'chkconfig' has no installation candidate


edit: I tried http://askubuntu.com/questions/221293/why-is-chkconfig-no-longer-available-in-ubuntu with no luck either.

I expect that I should use
upstart
or
systemd
. Can anyone have example or maybe another solution?

Answer

Here is a workaround for starting mongodb as a "service" in init.d :

#!/bin/sh
#title         :mongod
#author        :Bertrand Martel
#date          :15/08/2015
#description   :start/stop/restart mongod
#########################################
### install   :  cp mongod /etc/init.d/
#                update-rc.d mongod defaults
### uninstall :  update-rc.d -f mongodb remove

PATH_TO_MONGO=/usr/bin/mongod

#file containing all mongodb pid
PID_FILE=/tmp/mongodb.pid

case "$1" in
    start)
        echo "Starting mongodb service..."

        COMMAND_TO_RUN=`start-stop-daemon -S -b -m -p $PID_FILE -x $PATH_TO_MONGO& :`
        setsid sh -c $COMMAND_TO_RUN> /dev/null 2>&1 < /dev/null

        echo -e "\E[31;33m[ OK ]\E[0m"
        ;;
    stop)
        echo "Stopping mongodb service..."

        start-stop-daemon -K -q -p $PID_FILE

        echo -e "\E[31;33m[ OK ]\E[0m"
        ;;
    restart|reload)
        "$0" stop
        "$0" start
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $?

For install :

cp mongod /etc/init.d/

update-rc.d mongod defaults

For uninstall :

update-rc.d -f mongodb remove

starting :

/etc/init.d/mongod start

stopping :

/etc/init.d/mongod stop

restarting :

/etc/init.d/mongod restart

mongod is automatically launching at boot now.

gist : https://gist.github.com/akinaru/a3865fa441248f23d51e

Comments