Phusion Passenger is an Nginx module, which makes deploying Ruby and Ruby on Rails applications on Nginx a breeze. It follows the usual Ruby on Rails conventions, such as "Don’t-Repeat-Yourself" and ease of setup, while at the same time providing enough flexibility.

This users guide will teach you:

  • How to install Nginx with Phusion Passenger support.

  • How to configure Phusion Passenger.

  • How to deploy a Ruby on Rails application.

  • How to deploy a Rack-based Ruby application.

  • How to solve common problems.

This guide assumes that the reader is somewhat familiar with Nginx and with using the commandline.

1. Supported operating systems

Phusion Passenger works on any POSIX-compliant operating system. In other words: practically any operating system on earth, except Microsoft Windows.

Phusion Passenger for Nginx has been tested on:

Other operating systems have not been tested, but Phusion Passenger will probably work fine on them. Please report a bug or join our discussion list if it doesn’t.

2. Installing Phusion Passenger

2.1. Overview

As you might already know, Nginx does not support loadable modules, in contrast to most other web servers (e.g. Apache). Therefore, to install Phusion Passenger for Nginx, one must recompile and reinstall Nginx with Phusion Passenger support. There are two ways to do this:

  1. By running the Phusion Passenger installer for Nginx. This installer will guide you through the entire installation process, including downloading, compiling and installing Nginx. You should be able to get Nginx with Phusion Passenger support up-and-running in a matter of minutes. This is the recommended installation method.

  2. By manually configuring and compiling Nginx with Phusion Passenger support, through Nginx’s --add-module configure option. Generally, using our installer is easier, so you should only use this method if you’re already familiar with compiling Nginx.

Tip You might have to run the installation commands in the following sections as root. If the installer fails because of permission errors, it will tell you.

2.2. Specifying the correct Ruby installation

If your system has multiple Ruby installations — which is likely the case on MacOS X, or if you’ve also installed Ruby Enterprise Edition — then you will need to tell the operating system which Ruby installation to use, prior to running the Phusion Passenger installer. If you only have one Ruby installation (the case on most Linux systems), then you can skip this section because Phusion Passenger will automatically detect it.

To specify a Ruby installation, prepend your Ruby installation’s bin directory to the PATH environment variable. For example, if you have the following Ruby installations:

and you want to use the latter, then type:

export PATH=/opt/myruby/bin:$PATH

2.3. Installing Phusion Passenger for Nginx through the installer

2.3.1. Obtaining the Phusion Passenger files and running the installer

You must obtain the Phusion Passenger files in order to run the installer. This can be done either by installing the Phusion Passenger gem, or by downloading the source tarball.

Gem

First, install the Phusion Passenger gem by running:

gem install passenger

Next, run the Phusion Passenger installer for Nginx:

passenger-install-nginx-module

Please follow the instructions given by the installer.

Source tarball

The source tarball can be download from the Phusion Passenger website. Extract the tarball to whatever location you prefer. The Phusion Passenger files are to reside in that location permanently. For example, if you would like Phusion Passenger to reside in /opt/passenger-x.x.x, then type:

cd /opt
tar xzvf ~/YourDownloadsFolder/passenger-x.x.x.tar.gz

Next, run the Phusion Passenger installer for Nginx:

/opt/passenger-x.x.x/bin/passenger-install-nginx-module

Please follow the instructions given by the installer.

Important Please do not remove the passenger-x.x.x folder after installation. Furthermore, the passenger-x.x.x folder must be accessible by Nginx.

2.3.2. Non-interactive/automatic installation

By default, the installer is interactive. If you want to automate installation, then you can do so by passing various answers to the installer through command line options.

Please run the installer with --help for a list of available command line options.

2.4. Installing Phusion Passenger for Nginx manually

You can install Phusion Passenger as a normal Nginx module. To do this, run Nginx’s configure script with --add-module=/path-to-passenger-root/ext/nginx.

If you installed Phusion Passenger via the gem, then path-to-passenger-root can be obtained with the command:

passenger-config --root

This will probably output something along the lines of /usr/lib/ruby/gems/1.8/gems/passenger-x.x.x, so you’ll probably have to specify something like --add-module=/usr/lib/ruby/gems/1.8/gems/passenger-x.x.x/ext/nginx.

If you installed Phusion Passenger via a source tarball, then path-to-passenger-root is the directory which contains the Phusion Passenger source code. So if you extracted the Phusion Passenger source code to /opt/passenger-x.x.x, then you’ll have to specify --add-module=/opt/passenger-x.x.x/ext/nginx.

3. Deploying a Ruby on Rails application

Suppose you have a Ruby on Rails application in /webapps/mycook, and you own the domain www.mycook.com. You can either deploy your application to the virtual host’s root (i.e. the application will be accessible from the root URL, http://www.mycook.com/), or in a sub URI (i.e. the application will be accessible from a sub URL, such as http://www.mycook.com/railsapplication).

Note The default RAILS_ENV environment in which deployed Rails applications are run, is “production”. You can change this by changing the RailsEnv configuration option.

3.1. Deploying to a virtual host’s root

Add a server virtual host entry to your Nginx configuration file. The virtual host’s root must point to your Ruby on Rails application’s public folder.

Inside the server block, set passenger_enabled on.

For example:

http {
    ...

    server {
        listen 80;
        server_name www.mycook.com;
        root /webapps/mycook/public;
        passenger_enabled on;
    }

    ...
}

Then restart Nginx. The application has now been deployed.

3.2. Deploying to a sub URI

Suppose that you already have a server virtual host entry:

http {
    ...

    server {
        listen 80;
        server_name www.phusion.nl;
        root /websites/phusion;
    }

    ...
}

And you want your Ruby on Rails application to be accessible from the URL http://www.phusion.nl/rails.

To do this, make a symlink from your Ruby on Rails application’s public folder to a directory in the document root. For example:

ln -s /webapps/mycook/public /websites/phusion/rails

Next, set passenger_enabled on and add a [passenger_base_uri] option to the server block:

http {
    ...

    server {
        listen 80;
        server_name www.phusion.nl;
        root /websites/phusion;
        passenger_enabled on;        # <--- These lines have
        passenger_base_uri /rails;   # <--- been added.
    }

    ...
}

Then restart Nginx. The application has now been deployed.

Tip

You can deploy multiple Rails applications under a virtual host, by specifying passenger_base_uri multiple times. For example:

server {
    ...
    passenger_base_uri /app1;
    passenger_base_uri /app2;
    passenger_base_uri /app3;
}

3.3. Redeploying (restarting the Ruby on Rails application)

Deploying a new version of a Ruby on Rails application is as simple as re-uploading the application files, and restarting the application.

There are two ways to restart the application:

  1. By restarting Nginx.

  2. By creating or modifying the file tmp/restart.txt in the Rails application’s root folder. Phusion Passenger will automatically restart the application.

For example, to restart our example MyCook application, we type this in the command line:

touch /webapps/mycook/tmp/restart.txt

3.4. Migrations

Phusion Passenger is not related to Ruby on Rails migrations in any way. To run migrations on your deployment server, please login to your deployment server (e.g. with ssh) and type rake db:migrate RAILS_ENV=production in a shell console, just like one would normally run migrations.

3.5. Capistrano integration

See Capistrano recipe.

4. Deploying a Rack-based Ruby application

Phusion Passenger supports arbitrary Ruby web applications that follow the Rack interface.

Phusion Passenger assumes that Rack application directories have a certain layout. Suppose that you have a Rack application in /webapps/rackapp. Then that folder must contain at least three entries:

So /webapps/rackapp must, at minimum, look like this:

/webapps/rackapp
  |
  +-- config.ru
  |
  +-- public/
  |
  +-- tmp/

Suppose you own the domain www.rackapp.com. You can either deploy your application to the virtual host’s root (i.e. the application will be accessible from the root URL, http://www.rackapp.com/), or in a sub URI (i.e. the application will be accessible from a sub URL, such as http://www.rackapp.com/rackapp).

Note The default RACK_ENV environment in which deployed Rack applications are run, is “production”. You can change this by changing the rack_env configuration option.

4.1. Tutorial/example: writing and deploying a Hello World Rack application

First we create a Phusion Passenger-compliant Rack directory structure:

$ mkdir /webapps/rack_example
$ mkdir /webapps/rack_example/public
$ mkdir /webapps/rack_example/tmp

Next, we write a minimal "hello world" Rack application:

$ cd /webapps/rack_example
$ some_awesome_editor config.ru
...type in some source code...
$ cat config.ru
app = proc do |env|
    return [200, { "Content-Type" => "text/html" }, "hello <b>world</b>"]
end
run app

Finally, we deploy it by adding the following configuration options to the Apache configuration file:

http {
    ...
    server {
        listen 80;
        server_name www.rackexample.com;
        root /webapps/rack_example/public;
        passenger_enabled on;
    }
    ...
}

And we’re done! After an Nginx restart, the above Rack application will be available under the URL http://www.rackexample.com/.

4.2. Deploying to a virtual host’s root

Add a server virtual host entry to your Nginx configuration file. The virtual host’s root must point to your Rack application’s public folder. You must also set passenger_enabled on in the server block.

For example:

http {
    ...
    server {
        listen 80;
        server_name www.rackapp.com;
        root /webapps/rackapp/public;
        passenger_enabled on;
    }
    ...
}

Then restart Nginx. The application has now been deployed.

4.3. Deploying to a sub URI

Suppose that you already have a virtual host:

http {
    ...

    server {
        listen 80;
        server_name www.phusion.nl;
        root /websites/phusion;
        passenger_enabled on;
    }

    ...
}

And you want your Rack application to be accessible from the URL http://www.phusion.nl/rack.

To do this, make a symlink from your Rack application’s public folder to a directory in the document root. For example:

ln -s /webapps/rackapp/public /websites/phusion/rack

Next, set passenger_enabled on and add a [passenger_base_uri] option to the server block:

http {
    ...

    server {
        listen 80;
        server_name www.phusion.nl;
        root /websites/phusion;
        passenger_enabled on;        # <--- These lines have
        passenger_base_uri /rack;    # <--- been added.
    }

    ...
}

Then restart Apache. The application has now been deployed.

Tip

You can deploy multiple Rack applications under a virtual host, by specifying passenger_base_uri multiple times. For example:

server {
    ...
    passenger_base_uri /app1;
    passenger_base_uri /app2;
    passenger_base_uri /app3;
}

4.4. Redeploying (restarting the Rack application)

Deploying a new version of a Rack application is as simple as re-uploading the application files, and restarting the application.

There are two ways to restart the application:

  1. By restarting Nginx.

  2. By creating or modifying the file tmp/restart.txt in the Rack application’s root folder. Phusion Passenger will automatically restart the application.

For example, to restart our example application, we type this in the command line:

touch /webapps/rackapp/tmp/restart.txt

4.5. Rackup specifications for various web frameworks

This subsection shows example config.ru files for various web frameworks.

4.5.1. Camping

require 'rubygems'
require 'rack'
require 'camping'

##### Begin Camping application
Camping.goes :Blog

...your application code here...
##### End Camping application

run Rack::Adapter::Camping.new(Blog)

For Camping versions 2.0 and up, using run Blog as the final line will do.

4.5.2. Halcyon

require 'rubygems'
require 'halcyon'
$LOAD_PATH.unshift(Halcyon.root / 'lib')
Halcyon::Runner.load_config Halcyon.root/'config'/'config.yml'
run Halcyon::Runner.new

4.5.3. Mack

ENV["MACK_ENV"] = ENV["RACK_ENV"]
load("Rakefile")
require 'rubygems'
require 'mack'
run Mack::Utils::Server.build_app

4.5.4. Merb

require 'rubygems'
require 'merb-core'

Merb::Config.setup(
  :merb_root   => File.expand_path(File.dirname(__FILE__)),
  :environment => ENV['RACK_ENV']
)
Merb.environment = Merb::Config[:environment]
Merb.root = Merb::Config[:merb_root]
Merb::BootLoader.run

run Merb::Rack::Application.new

4.5.5. Ramaze

require "start"
Ramaze.trait[:essentials].delete Ramaze::Adapter
Ramaze.start :force => true
run Ramaze::Adapter::Base

4.5.6. Sinatra

require 'rubygems'
require 'sinatra'

root_dir = File.dirname(__FILE__)

set :environment, ENV['RACK_ENV'].to_sym
set :root,        root_dir
set :app_file,    File.join(root_dir, 'app.rb')
disable :run

run Sinatra::Application

5. Appendix A: About this document

The text of this document is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported License.

images/by_sa.png

Phusion Passenger is brought to you by Phusion.

images/phusion_banner.png

Phusion Passenger is a trademark of Hongli Lai & Ninh Bui.

6. Appendix B: Terminology

6.1. Application root

The root directory of an application that’s served by Phusion Passenger.

In case of Ruby on Rails applications, this is the directory that contains Rakefile, app/, config/, public/, etc. In other words, the directory pointed to by RAILS_ROOT. For example, take the following directory structure:

/apps/foo/       <------ This is the Rails application's application root!
   |
   +- app/
   |   |
   |   +- controllers/
   |   |
   |   +- models/
   |   |
   |   +- views/
   |
   +- config/
   |   |
   |   +- environment.rb
   |   |
   |   +- ...
   |
   +- public/
   |   |
   |   +- ...
   |
   +- ...

In case of Rack applications, this is the directory that contains config.ru. For example, take the following directory structure:

/apps/bar/      <----- This is the Rack application's application root!
   |
   +- public/
   |    |
   |    +- ...
   |
   +- config.ru
   |
   +- ...

In case of Python (WSGI) applications, this is the directory that contains passenger_wsgi.py. For example, take the following directory structure:

/apps/baz/      <----- This is the WSGI application's application root!
   |
   +- public/
   |    |
   |    +- ...
   |
   +- passenger_wsgi.py
   |
   +- ...

7. Appendix C: Spawning methods explained

At its core, Phusion Passenger is an HTTP proxy and process manager. It spawns Ruby on Rails/Rack/WSGI worker processes (which may also be referred to as backend processes), and forwards incoming HTTP request to one of the worker processes.

While this may sound simple, there’s not just one way to spawn worker processes. Let’s go over the different spawning methods. For simplicity’s sake, let’s assume that we’re only talking about Ruby on Rails applications.

7.1. The most straightforward and traditional way: conservative spawning

Phusion Passenger could create a new Ruby process, which will then load the Rails application along with the entire Rails framework. This process will then enter an request handling main loop.

This is the most straightforward way to spawn worker processes. If you’re familiar with the Mongrel application server, then this approach is exactly what mongrel_cluster performs: it creates N worker processes, each which loads a full copy of the Rails application and the Rails framework in memory. The Thin application server employs pretty much the same approach.

Note that Phusion Passenger’s version of conservative spawning differs slightly from mongrel_cluster. Mongrel_cluster creates entirely new Ruby processes. In programmers jargon, mongrel_cluster creates new Ruby processes by forking the current process and exec()-ing a new Ruby interpreter. Phusion Passenger on the other hand creates processes that reuse the already loaded Ruby interpreter. In programmers jargon, Phusion Passenger calls fork(), but not exec().

7.2. The smart spawning method

Note Smart spawning is only available for Ruby on Rails applications, not for Rack applications or WSGI applications.

While conservative spawning works well, it’s not as efficient as it could be because each worker process has its own private copy of the Rails application as well as the Rails framework. This wastes memory as well as startup time.

Worker processes and conservative spawning
Figure: Worker processes and conservative spawning. Each worker process has its own private copy of the application code and Rails framework code.

It is possible to make the different worker processes share the memory occupied by application and Rails framework code, by utilizing so-called copy-on-write semantics of the virtual memory system on modern operating systems. As a side effect, the startup time is also reduced. This is technique is exploited by Phusion Passenger’s smart and smart-lv2 spawn methods.

7.2.1. How it works

When the smart-lv2 spawn method is being used, Phusion Passenger will first create a so-called ApplicationSpawner server process. This process loads the entire Rails application along with the Rails framework, by loading environment.rb. Then, whenever Phusion Passenger needs a new worker process, it will instruct the ApplicationSpawner server to do so. The ApplicationSpawner server will create a worker new process that reuses the already loaded Rails application/framework. Creating a worker process through an already running ApplicationSpawner server is very fast, about 10 times faster than loading the Rails application/framework from scratch. If the Ruby interpreter is copy-on-write friendly (that is, if you’re running Ruby Enterprise Edition) then all created worker processes will share as much common memory as possible. That is, they will all share the same application and Rails framework code.

images/smart-lv2.png
Figure: Worker processes and the smart-lv2 spawn method. All worker processes, as well as the ApplicationSpawner, share the same application code and Rails framework code.

The smart spawn method goes even further, by caching the Rails framework in another process called the FrameworkSpawner server. This process only loads the Rails framework, not the application. When a FrameworkSpawner server is instructed to create a new worker process, it will create a new ApplicationSpawner to which the instruction will be delegated. All those ApplicationSpawner servers, as well as all worker processes created by those ApplicationSpawner servers, will share the same Rails framework code.

The smart-lv2 method allows different worker processes that belong to the same application to share memory. The smart method allows different worker processes - that happen to use the same Rails version - to share memory, even if they don’t belong to the same application.

Notes:

7.2.2. Summary of benefits

Suppose that Phusion Passenger needs a new worker process for an application that uses Rails 2.2.1.

You could compare ApplicationSpawner and FrameworkSpawner servers with stem cells, that have the ability to quickly change into more specific cells (worker process).

In practice, the smart spawning methods could mean a memory saving of about 33%, assuming that your Ruby interpreter is copy-on-write friendly.

Of course, smart spawning is not without gotchas. But if you understand the gotchas you can easily reap the benefits of smart spawning.

7.3. Smart spawning gotcha #1: unintential file descriptor sharing

Because worker processes are created by forking from an ApplicationSpawner server, it will share all file descriptors that are opened by the ApplicationSpawner server. (This is part of the semantics of the Unix fork() system call. You might want to Google it if you’re not familiar with it.) A file descriptor is a handle which can be an opened file, an opened socket connection, a pipe, etc. If different worker processes write to such a file descriptor at the same time, then their write calls will be interleaved, which may potentially cause problems.

The problem commonly involves socket connections that are unintentially being shared. You can fix it by closing and reestablishing the connection when Phusion Passenger is creating a new worker process. Phusion Passenger provides the API call PhusionPassenger.on_event(:starting_worker_process) to do so. So you could insert the following code in your environment.rb:

if defined?(PhusionPassenger)
    PhusionPassenger.on_event(:starting_worker_process) do |forked|
        if forked
            # We're in smart spawning mode.
            ... code to reestablish socket connections here ...
        else
            # We're in conservative spawning mode. We don't need to do anything.
        end
    end
end

Note that Phusion Passenger automatically reestablishes the connection to the database upon creating a new worker process, which is why you normally do not encounter any database issues when using smart spawning mode.

7.3.1. Example 1: Memcached connection sharing (harmful)

Suppose we have a Rails application that connects to a Memcached server in environment.rb. This causes the ApplicationSpawner to have a socket connection (file descriptor) to the Memcached server, as shown in the following figure:

+--------------------+
| ApplicationSpawner |-----------[Memcached server]
+--------------------+

Phusion Passenger then proceeds with creating a new Rails worker process, which is to process incoming HTTP requests. The result will look like this:

+--------------------+
| ApplicationSpawner |------+----[Memcached server]
+--------------------+      |
                            |
+--------------------+      |
| Worker process 1   |-----/
+--------------------+

Since a fork() makes a (virtual) complete copy of a process, all its file descriptors will be copied as well. What we see here is that ApplicationSpawner and Worker process 1 both share the same connection to Memcached.

Now supposed that your site gets Slashdotted and Phusion Passenger needs to spawn another worker process. It does so by forking ApplicationSpawner. The result is now as follows:

+--------------------+
| ApplicationSpawner |------+----[Memcached server]
+--------------------+      |
                            |
+--------------------+      |
| Worker process 1   |-----/|
+--------------------+      |
                            |
+--------------------+      |
| Worker process 2   |-----/
+--------------------+

As you can see, Worker process 1 and Worker process 2 have the same Memcache connection.

Suppose that users Joe and Jane visit your website at the same time. Joe’s request is handled by Worker process 1, and Jane’s request is handled by Worker process 2. Both worker processes want to fetch something from Memcached. Suppose that in order to do that, both handlers need to send a "FETCH" command to Memcached.

But suppose that, after worker process 1 having only sent "FE", a context switch occurs, and worker process 2 starts sending a "FETCH" command to Memcached as well. If worker process 2 succeeds in sending only one bye, F, then Memcached will receive a command which begins with "FEF", a command that it does not recognize. In other words: the data from both handlers get interleaved. And thus Memcached is forced to handle this as an error.

This problem can be solved by reestablishing the connection to Memcached after forking:

+--------------------+
| ApplicationSpawner |------+----[Memcached server]
+--------------------+      |                   |
                            |                   |
+--------------------+      |                   |
| Worker process 1   |-----/|                   |
+--------------------+      |                   |  <--- created this
                            X                   |       new
                                                |       connection
                            X <-- closed this   |
+--------------------+      |     old           |
| Worker process 2   |-----/      connection    |
+--------------------+                          |
          |                                     |
          +-------------------------------------+

Worker process 2 now has its own, separate communication channel with Memcached. The code in environment.rb looks like this:

if defined?(PhusionPassenger)
    PhusionPassenger.on_event(:starting_worker_process) do |forked|
        if forked
            # We're in smart spawning mode.
            reestablish_connection_to_memcached
        else
            # We're in conservative spawning mode. We don't need to do anything.
        end
    end
end

7.3.2. Example 2: Log file sharing (not harmful)

There are also cases in which unintential file descriptor sharing is not harmful. One such case is log file file descriptor sharing. Even if two processes write to the log file at the same time, the worst thing that can happen is that the data in the log file is interleaved.

To guarantee that the data written to the log file is never interleaved, you must synchronize write access via an inter-process synchronization mechanism, such as file locks. Reopening the log file, like you would have done in the Memcached example, doesn’t help.

7.4. Smart spawning gotcha #2: the need to revive threads

Another part of the fork() system call’s semantics is the fact that threads disappear after a fork call. So if you’ve created any threads in environment.rb, then those threads will no longer be running in newly created worker process. You need to revive them when a new worker process is created. Use the :starting_worker_process event that Phusion Passenger provides, like this:

if defined?(PhusionPassenger)
    PhusionPassenger.on_event(:starting_worker_process) do |forked|
        if forked
            # We're in smart spawning mode.
            ... code to revive threads here ...
        else
            # We're in conservative spawning mode. We don't need to do anything.
        end
    end
end

7.5. Smart spawning gotcha #3: code load order

This gotcha is only applicable to the smart spawn method, not the smart-lv2 spawn method.

If your application expects the Rails framework to be not loaded during the beginning of environment.rb, then it can cause problems when an ApplicationSpawner is created from a FrameworkSpawner, which already has the Rails framework loaded. The most common case is when applications try to patch Rails by dropping a modified file that has the same name as Rails’s own file, in a path that comes earlier in the Ruby search path.

For example, suppose that we have an application which has a patched version of active_record/base.rb located in RAILS_ROOT/lib/patches, and RAILS_ROOT/lib/patches comes first in the Ruby load path. When conservative spawning is used, the patched version of base.rb is properly loaded. When smart (not smart-lv2) spawning is used, the original base.rb is used because it was already loaded, so a subsequent require "active_record/base" has no effect.