Rails Deployment Options

There are many ways to deploy a Rails application. Sorting them all out and finding the right solution for your situation can be confusing. In this post I list and briefly describe popular choices.

Ruby Virtual Machine

Most Ruby implementations can run Rails. Some, however, cannot. The ability to run Rails is a major achievement for alternative Ruby VMs. For detailed comparisons check out Antonio Cangiano’s blog. He does the Ruby shootout.

  • MRI
    • 1.8 standard
    • Ruby 1.8.6 is the recommended version to use with Rails
  • YARV
    • 1.9 standard
    • Significantly faster than MRI
    • Rails is not yet fully compatible with Ruby 1.9
    • Many gems are not compatible with Ruby 1.9
  • JRuby
    • Java implementation of Ruby
    • Runs Rails
  • Rubinius
    • “Ruby in Ruby”
    • Runs Rails
  • Ruby Enterprise Edition
    • From the creators of Passenger
    • Fork of MRI
    • 33% less memory consumption on average when used with Passenger
  • MagLev
    • Commercial
    • Pending release
    • Lots of promise in terms of performance and features, but won’t run Rails for some time

For critical production applications, there are really only two choices to consider. If you are using Passenger, use Ruby Enterprise Edition. Otherwise, use the standard Ruby VM. The other implementations are progressing rapidly and developers are working hard to make them production ready.

Server Configuration

This is an active area. Notable configurations include:

  • nginx + mongrel | thin | ebb | fuzed (yaws)
    • nginx is a powerful lightweight frontend server/reverse proxy/load balancer that can withstand a real pounding
    • mongrel is the veteran backend web server for Ruby on Rails
    • thin is an evented backend server that’s faster than mongrel and supports unix socket connections
    • ebb is an evented backend server written in C that’s faster than thin and also supports unix socket connections, but it uses more memory than thin while idling
    • fuzed allows Rails to be served up by yaws, a server written in Erlang that provides an unparalleled degree of concurrency
  • Apache + Passenger (mod_rails) + Ruby Enterprise Edition
    • New and exciting deployment option for Apache
    • Easy to setup
    • Deploying an app can be as simple is uploading your app
    • mod_rails and Ruby Enterprise Edition, both developed by Phusion, together provide a 33% lower memory footprint (for Rails) on average
    • Integrated monitoring and load balancing; monitors Rails processes and starts/kills them as necessary based on demand
  • LiteSpeed
    • Commercial
    • Relatively easy to setup
    • Better performance than most other solutions
    • Despite its qualities, not a popular choice

I only mention LiteSpeed because of its performance. Few people actually use it for serious Rails deployments. I omitted lighttpd from the list because nginx has stolen the show. Ancient solutions like fastcgi were also omitted.

I use nginx + thin. I have not transitioned to ebb because of higher memory consumption (at least at idle). I included the fuzed project in my list because I find yaws and Erlang fascinating. Yaws puts Apache to shame when it comes to concurrency. I’m not sure how polished the fuzed project is, but it could be a contender. It’s also good to see cooperation between Ruby and Erlang. Mongrel, thin, and ebb are all good options. It all depends on your needs and preferences.

I have not tried out Passenger. It is being touted as a breakthrough solution because of how simple it makes deployment. My first impression is that it is more for deployment novices and conventional shared hosting environments. With WebFaction, you have the freedom and ability to build your own app stack. I’ve made this a breeze with a shake and bake shell script. Nginx is a better frontend server than Apache in its ability to serve static pages and with regard to memory usage. Unfortunately, Passenger only works with Apache.

Load Balancing

Load balancing allows your applications to scale horizontally.

  • Hardware
    • For very large applications
    • Most advanced
    • Expensive
  • HAProxy
    • For large applications
    • Very advanced
    • Difficult to setup
  • nginx-upstream-fair
    • Third party module for nginx
    • Adds fair load balancing to nginx (replaces standard round-robin load balancing)
    • Very simple to setup
    • Small to large applications

I use the nginx-upstream-fair module for load balancing. Written by Grzegorz Nosek, the module works very well and is so easy to setup that there is no reason not to do so.


To make sure that your processes are behaving, you need a process monitor.

I use monit. I haven’t tried the god gem, but I’ve heard good things.

Ruby on Rails Stack on WebFaction

I’ve created a shell script to build a complete Ruby on Rails stack (application environment) on WebFaction. Although written for WebFaction users, the script is fairly generic, aside from a few minor details. All you have to do is edit a few variable assignments (install path, rails app name, and service ports) at the beginning of the script and execute. In less than 20 minutes, your rails app will be up and running with nginx reverse proxying (and fair load balancing) to a pair of thin servers and with monit keeping watch.

In case you’re unfamiliar with thin, it’s the likely successor to mongrel. It uses mongrel’s excellent http parser, provides various overall enhancements, and offers a number of features mongrel lacks. I specifically chose to use thin on WebFaction because of its support for unix socket listeners. For more technical information, see the comments in the script and the accompanying README.markdown file.

What you get:

  • Ruby
  • RubyGems
  • Gems: rails, merb, mongrel, mongrel_cluster, thin, capistrano, termios, ferret, acts_as_ferret, god, sqlite3-ruby, mysql, and typo
  • Git
  • Nginx (with nginx-upstream-fair third party module)
  • Monit
  • Startup scripts and working default configuration files for nginx and monit

UPDATE: New script with Passenger on nginx!

I will try to keep this script reasonably up to date at GitHub.

mongrel_cluster with Nonconsecutive Ports

Need to run mongrel_cluster with nonconsecutive ports? No problem.

WebFaction assigns ports to its users through the control panel. The panel will not assign you consecutive ports. You can still use ports that aren’t assigned to you, but I assume that WebFaction does not want you to. Running mongrel_cluster without stretching or breaking the rules requires some effort. Unmodified, mongrel_cluster will only spawn mongrel_rails listeners on consecutive ports. Configuration is limited to specifying the first port and the number of instances. The situation with WebFaction requires a more precise way to configure ports. We will need to modify the mongrel_cluster code. All we need to do is add one line.

The file requiring modification is lib/mongrel_cluster/init.rb inside the mongrel_cluster gem directory. The easiest way to find and open this file for editing is to execute the following command:

nano `locate lib/mongrel_cluster/init.rb`

Locate the read_options method. In version 1.0.5, it should read:

def read_options
    @options = {
        "environment" => ENV['RAILS_ENV'] || "development",
        "port" => 3000,
        "pid_file" => "tmp/pids/mongrel.pid",
        "log_file" => "log/mongrel.log",
        "servers" => 2
    conf = YAML.load_file(@config_file)
    @options.merge! conf if conf

    process_pid_file @options["pid_file"]
    process_log_file @options["log_file"]

    start_port = end_port = @only
    start_port ||=  @options["port"].to_i
    end_port ||=  start_port + @options["servers"] - 1
    @ports = (start_port..end_port).to_a

Add the following line to the end of the method:

@ports = @options["ports"] if @options["ports"] && !@only

The addition recognizes a parameter named ‘ports’ in config/mongrel_cluster.yml. Unless a single port is specified on the command line using the --only option, ‘ports’ will be respected over the ‘port’ and ‘servers’ parameters used to specify a continuous range. The ‘ports’ parameter should be accompanied by an array of integers in YAML format. An example mongrel_cluster.yml file that defines nonconsecutive ports follows:

cwd: /home/user/webapps/railsapp
environment: production
user: user
group: user
log_file: log/mongrel.log
pid_file: tmp/pids/mongrel.pid
- 3333
- 3335
- 3359
- 3401

The one line addition does not give you the ability to define discontinuous ports on the command line. You must edit mongrel_cluster.yml to do so.

SSH Public Key Authentication

If you use ssh often, you should use public key authentication. It’s more secure than password authentication and with ssh-agent, you don’t have to enter your key’s passphrase each and every time you login. I use public key authentication to access my WebFaction shell account. This post details how to set up SSH public key authentication.


~/.ssh Directory Creation

User specific ssh data is stored in the ~/.ssh directory. On both the client and the server execute:

mkdir ~/.ssh
chmod 700 ~/.ssh

If the directory already exists, make sure that the permissions are set to 700 (rwx------).

Key Pair Generation

Create the key pair on the client with:

ssh-keygen -q -f ~/.ssh/id_rsa -t rsa

Enter a passphrase when asked. It should be at least 16 characters long and not your account password.

Public Half Key Dissemination

Upload id_rsa.pub to the server with:

scp ~/.ssh/id_rsa.pub username@remote-machine:~/.ssh/

Replace username and remote-machine accordingly.

The public key data must be appended into the ~/.ssh/authorized_keys file on the server:

cat ~/id_rsa.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
rm ~/.ssh/id_rsa.pub

SSH into Remote Machine

The first time you ssh into the remote machine from the client, execute:

ssh -o PreferredAuthentications=publickey username@remote-machine

Again, replace username and remote-machine accordingly. You will be asked to enter your passphrase.

Add Passphrase to Keychain

Entering the private key passphrase each time you ssh into the remote machine can be frustrating. If you are using Mac OS X 10.5 (Leopard) and higher, you have the option to save the passphrase in the Apple Keychain at the passphrase prompt. This feature doesn’t come standard in 10.4 (Tiger) and lower. However, SSHKeychain provides such functionality. If your using another Unix-like system, see the first resource below.

SSHKeychain Primer

I have several iMac G3s that I still use regularly and I’ve installed SSHKeychain on them. Setting up SSHKeychain is a little tricky, so I’ll explain the basics here.

SSHKeychain is installed through an installer rather than by drag-and-drop. Once installed, open up SSHKeychain from the Applications directory. Open up the Preferences dialog box. You can do this three ways. You can click “SSHKeychain” at the top left of the menubar and select “Preferences…”, click the keychain icon at the top right of the menubar and select “Preferences…”, or right click/click and hold the icon in the dock and select “Preferences…”. Select the “Environment” tab and check the “Manage (and modify) global environment variables”. (That’s what I missed at first.) Select the “SSH Keys” tab and remove the default values using the minus sign button (unless those private keys actually do exist). Select the plus sign button and enter the full path of the private key you just created. For example: /Users/username/.ssh/id_rsa. Close the Preferences dialog box, and click “Agent” and select “Add all keys…”. You can find “Agent” on the menubar or the dock menu. You will be prompted for the private key passphrase and have the option to add the passphrase to the Apple keychain. I had a problem typing in the entire passphrase in the password field. I solved this by typing it in TextMate and doing a copy and paste. If you have to do this, make sure to copy meaningless text afterward. You really don’t want your passphrase to be exposed on the clipboard for any significant length of time. Before you ssh into your servers using public key authentication managed by SSHKeychain, restart your computer. It should work nicely afterward.

Disabling Standard Password Authentication

If you only want public key authentication to be used to login to a remote machine via ssh, see the second resource on how to disable all other means.

Other Resources

  1. OpenSSH Public Key Authentication
  2. Secure your SSH server with Public/Private key authentification
  3. Securing ssh-agent on Mac OS X 10.5 (Leopard)
  4. SSH with Keys HOWTO
  5. Take Controll of SSH, Draft Excerpt: Public Key Authentication