Mar 27

Customized Mongrel Startup Script

This shell script allows to start and stop bunch of "Rails":http://www.rubyonrails.com application on "Mongrel":http://mongrel.rubyforge.org/ webserver. This is "Tim Morgan's":http://timmorgan.org/ script, while I added ability to customize port, rails environment and directory for every app while respecting default values.

This shell script allows to start and stop bunch of "Rails":http://www.rubyonrails.com application on "Mongrel":http://mongrel.rubyforge.org/ webserver. This is "Tim Morgan's":http://timmorgan.org/ script, while I added ability to customize port, rails environment and directory for every app while respecting default values.

I use it on linux development machine where there is no need for mongrel_cluster and I do not want to make extra configuration.

We can save this script as /etc/init.d/mongrel and start|restart|stop all mongrels with /etc/init.d/mongrel start (or stop|restart). And to configure for startup we can use:

# redhat
sudo /sbin/chkconfig --level 345 mongrel on
#debian/ubuntu
sudo /usr/sbin/update-rc.d -f mongrel defaults

And here is script:

#!/usr/bin/env ruby
#
# mongrel Startup script for Mongrel by Tim Morgan, modified by bmihelac
#
# chkconfig: - 85 15
# description: mongrel manages Mongrel
#

# this would add one mongrels for these two apps on 
# ports 8000 and 8001, mephisto would be started in production
apps = [
  {:app => 'myapp'},
  {:app => 'mephisto', :environment => 'production'},
]

default_port = 8000
default_options = {
  :app_dir => '/home/rails',
  :environment => 'production'
}

if ['stop', 'restart'].include? ARGV.first
  apps.each do |app|
    options = default_options.merge(app)
    path = File.join options[:app_dir], options[:app]
    puts "Stopping #{path}..." 
    `mongrel_rails stop -c #{path} -P log/mongrel.pid`
  end
end

if ['start', 'restart'].include? ARGV.first
  apps.each do |app|
    options = default_options.merge(app)
    path = File.join options[:app_dir], options[:app]
    port = options[:port] || default_port
    puts "Starting #{options[:app]} on #{port}..." 
    `mongrel_rails start -d -p #{port} -e #{options[:environment]} -c #{path} -P log/mongrel.pid`
    default_port = port + 1
  end
end

unless ['start', 'stop', 'restart'].include? ARGV.first
    puts "Usage: mongrel {start|stop|restart}" 
    exit
end