Last Updated: February 25, 2016
·
2.762K
· Bruno Coimbra

Debian-like init.d script for Unicorn

Actually I use the follow script to start/stop my unicorn rails processes. The script should be placed into /etc/init.d directory, in this case, the canonical name of file is /etc/init.d/unicorn.

Note: To this script work the variables below should be correctly set.

#!/bin/bash
# /etc/init.d/unicorn

# ### BEGIN INIT INFO
# Provides:          unicorn
# Required-Start:    $network $remote_fs $local_fs
# Required-Stop:     $network $remote_fs $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Stop/start unicorn
### END INIT INFO

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

PROJ_NAME="<YOUR_PROJECT_NAME>"
PID_FILE=/var/run/$PROJ_NAME/unicorn.pid
OLD_PID_FILE=$PID_FILE.oldbin
PROJ_DIR=/var/www/$PROJ_NAME
TAG='[unicorn]'
UNICORN_CONFIG=config/unicorn.rb
DEPLOY_USER=deploy
RAILS_ENV=${RAILS_ENV:-production}

# Start the service
start() {
    if [[ -f $PID_FILE ]]; then
        logger -sit $TAG "There is a PID file in $PID_FILE. Service should be running"
        exit 1
    else
        logger -sit "$TAG" "Trying to start server..."
        su $DEPLOY_USER -c "bash -c 'cd $PROJ_DIR ; bin/unicorn_rails -c $UNICORN_CONFIG -E $RAILS_ENV -D'"
        if [[ $? == 0 ]]; then
            logger -sit "$TAG" "server started"
        else
            logger -sit "$TAG" "FAILED to start server"
            exit 1
        fi
    fi
}

# Stop the service
stop() {
        su $DEPLOY_USER -c "kill -TERM $(cat $PID_FILE)"
        sleep 2
        if [[ ! -f $PID_FILE ]]; then
                logger -sit "$TAG" "Server stoped"
        else
                logger -sit "$TAG" "FAILED to stop server"
                exit 1
        fi
}

# Reload service
reload() {
    logger -sit "$TAG" "Trying to reload server"
    kill -USR2 $(cat $PID_FILE)
    sleep 1
    if [[ -f $OLD_PID_FILE ]]; then
        logger -sit "$TAG" "Server reloaded"
    else
        logger -sit "$TAG" "FAILED to reload server"
        exit 1
    fi
}

restart() {
        logger -sit "$TAG" "Restarting server"
        kill -HUP $(cat $PID_FILE)
}

### main logic ###
case "$1" in
    start)
        start
        ;;

    stop)
        stop
        ;;

    restart)
        restart
        ;;
    reload)
        reload
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart|reload}"
        exit 1
esac

exit 0

To make the system run this script after boot, you just need to run the follow commands:

$ chmod +x /etc/init.d/unicorn
$ update-rc.d unicorn defaults