Starting a Rails instance automatically on boot on Ubuntu Server

Posted by sam Thu, 24 Mar 2011 15:24:00 GMT

Audience

The follow steps will allow you to start a Rails instance automatically on boot under an Ubuntu instance in the simplest possible way. If you know about alternative Rails servers, deployment architectures beyond “webserver + mod_proxy + Mongrel” and the like then you are not the intended audience for this post.

Below is the simplest possible thing you can do to start a Rails instance automatically when you reboot your Ubuntu server, in keeping with the startup scripts that are already there. I hope that this is useful for someone starting out.

Steps

  1. save the following script in a file called ‘rails’ within the /tmp directory
  2. edit the USER, PORT, RAILS_ROOT variables to suit your application
  3. run the following commands:
sudo cp /tmp/rails /etc/init.d
sudo update-rc.d rails defaults

Reboot and test.

Script

#! /bin/sh
### BEGIN INIT INFO
# Provides:          rails
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start a Rails instance
# Description:       Do the simplest thing possible in keeping with
#             upstart to spin up a single Rails instance.
### END INIT INFO

# Author: Sam Pointer 
#
# Do NOT "set -e"

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
USER="myappuser"
PORT=3000
RAILS_ROOT="/home/myapp/current"
COMMAND="ruby script/server -e production -p $PORT -d"
DESCRIPTION="Rails instance"

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

#
# Function that starts the daemon/service
#
do_start()
{
    # Return
    #   0 if daemon has been started
    #   1 if daemon was already running
    #   2 if daemon could not be started
    su -c "cd $RAILS_ROOT && $COMMAND" $USER
}

case "$1" in
  start)
        [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESCRIPTION"
        do_start
        case "$?" in
                0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
                2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
        ;;
esac
Trackbacks

Use the following link to trackback from your own site:
http://blog.sam-pointer.com/trackbacks?article_id=94