I have recently built some web apps with Ruby on Rails and needed to serve them up in a production environment using Ubuntu 12.04, Nginx & Unicorn. There are many ways of installing RoR (Ruby on Rails) but this is the method I currently use to deploy my Ubuntu Rails servers. Apt is used as much as possible in this tutorial although the actual Rails install is done via gem (once Ruby 1.9.3 is installed via apt).
Currently I write Rails apps on Mac OSX then deploy to EC2 VPS running Ubuntu 12.04 Nginx & Unicorn. I favor Nginx over Apache and Unicorn over Mongrel, Thin or Passanger as they offer better perfomance & use less system resources – ideal for running Rails apps on small VPS / cloud servers like EC2, Rackspace, Bytemark, Linode etc.
Ubuntu Ruby 1.9.3 Install
I use apt-get to install Ruby 1.9.3 – some people prefer to use RVM but I don’t have a requirement to swap Ruby binary versions on production servers.
1
sudo apt-get install ruby1.9.3-dev ruby1.9.3
Install the Ubuntu Build Essentials package or Ruby will fail to build gems with a make error:
1
sudo apt-get install build-essential
Gem Install Rails on Ubuntu 12.04
Next install Ruby on Rails by entering the following gem command:
1
gem install rails
If all goes well this should give you an output similar to:
123456789101112131415161718192021222324252627
Building native extensions. This could take a while...
Fetching: rdoc-3.12.gem (100%)Depending on your version of ruby, you may need to install ruby rdoc/ri data:
<= 1.8.6 : unsupported= 1.8.7 : gem install rdoc-data; rdoc-data --install
= 1.9.1 : gem install rdoc-data; rdoc-data --install
>= 1.9.2 : nothing to do! Yay!
Fetching: railties-3.2.9.gem (100%)Fetching: bundler-1.2.2.gem (100%)Fetching: rails-3.2.9.gem (100%)Successfully installed json-1.7.5
Successfully installed rdoc-3.12
Successfully installed railties-3.2.9
Successfully installed bundler-1.2.2
Successfully installed rails-3.2.9
5 gems installed
Installing ri documentation for json-1.7.5...
Installing ri documentation for rdoc-3.12...
Installing ri documentation for railties-3.2.9...
Installing ri documentation for bundler-1.2.2...
Installing ri documentation for rails-3.2.9...
Installing RDoc documentation for json-1.7.5...
Installing RDoc documentation for rdoc-3.12...
Installing RDoc documentation for railties-3.2.9...
Installing RDoc documentation for bundler-1.2.2...
Installing RDoc documentation for rails-3.2.9...
Next I copy over my Rails app using Rsync & SSH (you could create a test app with rails blog or git clone a project). Change into the rails project dir and run:
1
bundle install
At this point you might get some errors I had the following dep failuires (your milage will vary depending on your Rails app dependencies):
Nokogirl Error gem_make.out
123
Gem files will remain installed in /var/lib/gems/1.9.1/gems/nokogiri-1.5.5 for inspection.
Results logged to /var/lib/gems/1.9.1/gems/nokogiri-1.5.5/ext/nokogiri/gem_make.out
I required the following:
1
sudo apt-get install libxslt-dev libxml2-dev
Rails sqlite3 error: An error occurred while installing sqlite3 (1.3.6), and Bundler cannot continue.
I fixed this by installing the dev for sqlite3 (I already had sqlite3 installed):
1
sudo apt-get install sqlite3 libsqlite3-dev
All gems for my Rails app then built fine.
Rails Error: I could not find a JavaScript runtime. See sstephenson/ExecJS (GitHub) for a list of available runtimes (ExecJS::RuntimeUnavailable).
Next I ran rails server and got the following Rails Error: I could not find a JavaScript runtime. See sstephenson/ExecJS (GitHub) for a list of available runtimes (ExecJS::RuntimeUnavailable). I fixed this by installing node.js on Ubuntu with:
1
sudo apt-get install nodejs
Test that your rails app runs with:
1
rails server
Now we have confirmed the app starts and functions using Webrick it’s time to install Unicorn on Ubuntu and configure Nginx.
Install Unicorn for your Rails Server (sits behind Nginx)
Webrick should never be used in a production environment it’s a basic server design for development testing, in this tutorial I use Unicorn for it’s lower foot print and greater performance.
Install Nginx (latest) on Ubuntu 12.04 using APT & the Nginx repo
The next step is installing and configuring Nginx, I install directly from nginx.org using their apt repository it’s a newer version than the one available in the Ubuntu repo, although I expect the Ubuntu repo version would work (un-tested).
Add the following two lines to your /etc/apt/sources.lst file:
12
deb https://nginx.org/packages/ubuntu/ precise nginx
deb-src https://nginx.org/packages/ubuntu/ precise nginx
Install the Nginx key (or apt will give you an error):
# This is example contains the bare mininum to get nginx going with# Unicorn or Rainbows! servers. Generally these configuration settings# are applicable to other HTTP application servers (and not just Ruby# ones), so if you have one working well for proxying another app# server, feel free to continue using it.## The only setting we feel strongly about is the fail_timeout=0# directive in the "upstream" block. max_fails=0 also has the same# effect as fail_timeout=0 for current versions of nginx and may be# used in its place.## Users are strongly encouraged to refer to nginx documentation for more# details and search for other example configs.# you generally only need one nginx worker unless you're serving# large amounts of static files which require blocking disk readsworker_processes 1;
# # drop privileges, root is needed on most systems for binding to port 80# # (or anything < 1024). Capability-based security may be available for# # your system and worth checking out so you won't need to be root to# # start nginx to bind on 80user nobody nogroup; # for systems with a "nogroup"# user nobody nobody; # for systems with "nobody" as a group instead# Feel free to change all paths to suite your needs here, of coursepid /tmp/nginx.pid;
error_log /tmp/nginx.error.log;
events { worker_connections 1024; # increase if you have lots of clients accept_mutex off; # "on" if nginx worker_processes > 1# use epoll; # enable for Linux 2.6+# use kqueue; # enable for FreeBSD, OSX}http {# nginx will find this file in the config directory set at nginx build time include mime.types;
# fallback in case we can't determine a type default_type application/octet-stream;
# click tracking! access_log /tmp/nginx.access.log combined;
# you generally want to serve static files with nginx since neither# Unicorn nor Rainbows! is optimized for it at the moment sendfile on;
tcp_nopush on; # off may be better for *some* Comet/long-poll stuff tcp_nodelay off; # on may be better for some Comet/long-poll stuff# we haven't checked to see if Rack::Deflate on the app server is# faster or not than doing compression via nginx. It's easier# to configure it all in one place here for static files and also# to disable gzip for clients who don't get gzip/deflate right.# There are other gzip settings that may be needed used to deal with# bad clients out there, see https://wiki.nginx.org/NginxHttpGzipModule gzip on;
gzip_http_version 1.0;
gzip_proxied any;
gzip_min_length 500;
gzip_disable "MSIE [1-6]\.";
gzip_types text/plain text/html text/xml text/css
text/comma-separated-values
text/javascript application/x-javascript
application/atom+xml;
# this can be any application server, not just Unicorn/Rainbows! upstream app_server {# fail_timeout=0 means we always retry an upstream even if it failed# to return a good HTTP response (in case the Unicorn master nukes a# single worker for timing out).# for UNIX domain socket setups: server unix:/tmp/.sock fail_timeout=0;
# for TCP setups, point these to your backend servers# server 192.168.0.7:8080 fail_timeout=0;# server 192.168.0.8:8080 fail_timeout=0;# server 192.168.0.9:8080 fail_timeout=0;} server {# enable one of the following if you're on Linux or FreeBSD# listen 80 default deferred; # for Linux# listen 80 default accept_filter=httpready; # for FreeBSD# If you have IPv6, you'll likely want to have two separate listeners.# One on IPv4 only (the default), and another on IPv6 only instead# of a single dual-stack listener. A dual-stack listener will make# for ugly IPv4 addresses in $remote_addr (e.g ":ffff:10.0.0.1"# instead of just "10.0.0.1") and potentially trigger bugs in# some software.# listen [::]:80 ipv6only=on; # deferred or accept_filter recommended client_max_body_size 4G;
server_name _;
# ~2 seconds is often enough for most folks to parse HTML/CSS and# retrieve needed images/icons/frames, connections are cheap in# nginx so increasing this is generally safe... keepalive_timeout 5;
# path for static files root /path/to/app/current/public;
# Prefer to serve static files directly from nginx to avoid unnecessary# data copies from the application server.## try_files directive appeared in in nginx 0.7.27 and has stabilized# over time. Older versions of nginx (e.g. 0.6.x) requires# "if (!-f $request_filename)" which was less efficient:# https://bogomips.org/unicorn.git/tree/examples/nginx.conf?id=v3.3.1#n127 try_files $uri/index.html $uri.html $uri @app;
location @app {# an HTTP header important enough to have its own Wikipedia entry:# https://en.wikipedia.org/wiki/X-Forwarded-For proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# enable this if you forward HTTPS traffic to unicorn,# this helps Rack set the proper URL scheme for doing redirects:# proxy_set_header X-Forwarded-Proto $scheme;# pass the Host: header from the client right along so redirects# can be set properly within the Rack application proxy_set_header Host $http_host;
# we don't want nginx trying to do something clever with# redirects, we set the Host: header above already. proxy_redirect off;
# set "proxy_buffering off" *only* for Rainbows! when doing# Comet/long-poll/streaming. It's also safe to set if you're using# only serving fast clients with Unicorn + nginx, but not slow# clients. You normally want nginx to buffer responses to slow# clients, even with Rails 3.1 streaming because otherwise a slow# client can become a bottleneck of Unicorn.## The Rack application may also set "X-Accel-Buffering (yes|no)"# in the response headers do disable/enable buffering on a# per-response basis.# proxy_buffering off; proxy_pass https://app_server;
}# Rails error pages error_page 500 502 503 504 /500.html;
location= /500.html { root /path/to/app/current/public;
}}}
Make sure the directories for the logs exist, next start nginx:
1
/etc/init.d/nginx start
Visit your site in a browser and you should see your RoRs app running, if Nginx is giving you a 503 you either miscongiured Nginx or Unicorn is not running (you must run Unicorn and Nginx).