How to deploy Ruby Rack app with NGINX How to deploy Ruby Rack app with NGINX nginx nginx

How to deploy Ruby Rack app with NGINX


here is a basic nginx config for the case you are going with unicorn/thin solution:

upstream rack_upstream {  server 127.0.0.1:9292;}server {  listen       80;  server_name  domain.tld;  charset UTF-8;  location / {    proxy_pass http://rack_upstream;    proxy_redirect     off;    proxy_set_header   Host             $host;    proxy_set_header   X-Real-IP        $remote_addr;    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;  }  location ~* ^.+\.(jpg|jpeg|gif|png|css|js)$ {    root /path/to/static/files;  }}

if you run nginx as root you'll can serve your site on port 80.

otherwise change listen 80 to listen SOME-AVAILABLE-PORT

replace domain.tld with your site name

also you can add extensions of files to be served by nginx in the (jpg|jpeg|gif|png|css|js) regex, delimiting them by |

see more at:

http://wiki.nginx.org/DirectiveIndex

http://wiki.nginx.org/ServerBlockExample

http://wiki.nginx.org/FullExample


The easiest thing is probably passenger which allows nginx to serve (among other things) any rack based app. It's pretty easy to setup, but since nginx doesn't have loadable modules you do have to install nginx from source (the installer handles all this for you).

Another popular way is to have nginx proxy to unicorn. Unicorn is a ruby webserver that can host any rack app. Typically you let nginx handle static assets and send the rest to unicorn. Unicorn has some nice features compared to thin, mongrel etc, for example it handles seamless restarts pretty much out of the box.


Deploying nginx+passenger is pretty easy when use precompiled passenger binaries (for Debian/Ubuntu). It is important to have following directory structure of your project:

/var/www/my_app:    \-- public/   <- public root of webserver    \-- config.ru <- that's where you place hello world    \-- tmp        \-- restart.txt

nginx config (probably e.g. in /etc/nginx/sites-available/my_site):

server {  listen 80;  server_name example.com;  root /var/www/my_app/public;  passenger_enabled on;  passenger_ruby /usr/bin/ruby;    }

When you want to restart your application, simply run

touch /var/www/my_app/tmp/restart.txt

To enable your site on Debian, create a symlik

ln -s /etc/nginx/sites-available/my_site /etc/nginx/sites-enabled/my_site

and reload nginx /etc/init.d/nginx reload