Unicorn is a very fast app server for Ruby on Rails. You just have to go to the APP_ROOT and type in “unicorn_rails”. And your app is running.
The problem with that is, if your server reboots your app is down. And you have to start it again by hand. That is not so cool!
Wouldn’t it be cool if you could start your Ruby on Rails like that:
/etc/init.d/unicorn start
and stop it like that:
/etc/init.d/unicorn stop
like all other services on Linux? And after a reboot unicorn starts automatically.
That is possible. Just use this script here for starting and stopping unicorn.
#!/bin/bash
### BEGIN INIT INFO
# Provides: unicorn
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start daemon at boot time
# Description: Enable service provided by daemon.
### END INIT INFO
UNICORN=/var/lib/gems/1.9.1/bin/unicorn_rails
KILL=/bin/kill
APP_ROOT=/opt/myapp
PID=$APP_ROOT/tmp/pids/unicorn.pid
GEM_HOME=/var/lib/gems/1.9.1/gems/
sig () {
test -s "$PID" && kill -$1 `cat $PID`
}
case "$1" in
start)
echo "Starting unicorn..."
cd $APP_ROOT
$UNICORN -D -E production
;;
stop)
sig QUIT && exit 0
echo >&2 "Not running"
;;
restart)
$0 stop
$0 start
;;
status)
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
;;
esac
Just customize the paths to your server and place the script in “/etc/init.d”. And ensure that the script is executable.
chmod ugo+x <YOUR_SCRIPT>
Than navigate to the direcotry “/etc/init.d” and execute this here:
update-rc.d <YOUR_SCRIPT> defaults
That will add your script to the default runlevels. So that your script will be executed by every reboot.