Setup Rails On Amazon Server Ubuntu Instance with Nginx and Unicorn

Posted by ongraph · November 18, 2014 · 8 Min read

Table of contents

MANAGE SERVER WITH PUTTY

– Once you setup your amazon server and get an amazon instance, you should have a private key private_key.pem
– Open puttygen
– Browse private_key.pem
– Generate .ppk file
– Open Putty
– Enter IP Address in session and save session with a name. 
– Click SSH/Auth and browse private key generated by puttygen
– Double click on the name of saved session, you will get your server window, type password of your instance.
– Now, here you go. 

 

Step 1:- Installing Ruby

Choose the version of Ruby you want to install:
   The first step is to install some dependencies for Ruby.
   I. sudo apt-get update
   II. sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev

a) Choose one method.

    1. Using Rbenv :-

        $ cd ~
        $git clone git://github.com/sstephenson/rbenv.git .rbenv
        $ echo ‘export PATH=”$HOME/.rbenv/bin:$PATH”‘ >> ~/.bashrc
        $ echo ‘eval “$(rbenv init -)”‘ >> ~/.bashrc
        $ exec $SHELL
        
        $ git clone git://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
        $ echo ‘export PATH=”$HOME/.rbenv/plugins/ruby-build/bin:$PATH”‘ >> ~/.bashrc
        $ exec $SHELL
        
        $ rbenv install 2.1.3
        $ rbenv global 2.1.3
        $ ruby -v

 

     2. Using rvm :-

        $ sudo apt-get install libgdbm-dev libncurses5-dev automake libtool bison libffi-dev
        $ curl -L https://get.rvm.io | bash -s stable
        $ source ~/.rvm/scripts/rvm
        $ echo “source ~/.rvm/scripts/rvm” >> ~/.bashrc
        $ rvm install 2.1.3
        $ rvm use 2.1.3 –default
        $ ruby -v

  The last step is to tell Rubygems not to install the documentation for each package locally

        $ echo “gem: –no-ri –no-rdoc” > ~/.gemrc

 

Step 2:- Installing Git
 
 a) $ sudo apt-get update
 b) $ sudo apt-get install git

 

Step 3:- Configuring Git

 a) $ git config –global user.name “YOUR NAME”
 b) $ git config –global user.email “YOUR@EMAIL.com”
 

Step 4:- Installing Rails

 a) $ gem install rails
   If you’re using rbenv, you’ll need to run the following command to make the rails executable available:
   $ rbenv rehash
   
   To check rails version
   $ rails -v
   #4.1.6 

 

DATABASE SETUP
   

Step 5:- Setting Up MySQL

 a) $ sudo apt-get update
 b) $ sudo apt-get install mysql-server mysql-client libmysqlclient-dev

 
Step 6:- Setting Up PostgreSQL

 $ sudo sh -c “echo ‘deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main’ > /etc/apt/sources.list.d/pgdg.list”
 $ wget –quiet -O – http://apt.postgresql.org/pub/repos/apt/ACCC4CF8.asc | sudo apt-key add –
 $ sudo apt-get update
 $ sudo apt-get install postgresql-common
 $ sudo apt-get install postgresql-9.3 libpq-dev

    The postgres installation doesn’t setup a user for you, so you’ll need to follow these steps to create a user with permission    to create databases. Feel free to replace shoaib with your username.

  $ sudo -u postgres createuser shoaib -s

 
 # If you would like to set a password for the user, you can do the following
  $ sudo -u postgres psql
  $ postgres=# \password shoaib
  
  

Step 7:- Install Nginx

 Step One :-
   $ sudo apt-get update
   $ sudo apt-get install nginx
   
 Step Two Check your Web Server
   When you have your servers IP address or domain, enter it into your browser’s address bar:
   – server_domain_name_or_IP
   You should see the default Nginx landing page:
   
 Step Three Manage the Nginx Process
    a) To stop your web server, you can type:
       $ sudo service nginx stop
       
    b) To start the web server when it is stopped, type:
       $ sudo service nginx start
    
    c) To stop and then start the service again, type:
       $ sudo service nginx restart
       
    We can make sure that our web server will restart automatically when the server is rebooted by typing:

       $ sudo update-rc.d nginx defaults

 

    This should already be enabled by default, so you may see a message like this:
       System start/stop links for /etc/init.d/nginx already exist.

Step 8:- Clone source code of project

  a) $ git clone
  b) $ bundle install
  c) $ RAILS_ENV=production rake db:create db:migrate db:seed
  d) $ RAILS_ENV=production rake assets:precompile
  

Step 9:- Configure Unicorn 

  a) Add gem ‘unicorn’ in production group in Gemfile.
    $ nano Gemfile
      gem ‘unicoen’, group: :production
    
    Save and exit by pressing CTRL+X and confirming with Y.
    
  b) bundle install

  c) Make a unicorn.rb file in config folder. ie. config/unicorn.rb
    $ touch config/unicorn.rb    # To create an empty file
    $ nano config/unicorn.rb     # To open the file
    

#unicorn.rb contains
       # config/unicorn.rb
        pid “tmp/pids/unicorn.pid”
        stderr_path “log/unicorn.log”
        stdout_path “log/unicorn.log”
        # Unicorn socket
        listen “/tmp/unicorn.seladex.sock”
        worker_processes Integer(ENV[“WEB_CONCURRENCY”] || 5)
        timeout 30
        preload_app true
        before_fork do |server, worker|
          Signal.trap ‘TERM’ do
            puts ‘Unicorn master intercepting TERM and sending myself QUIT instead’
            Process.kill ‘QUIT’, Process.pid
          end
          defined?(ActiveRecord::Base) and
            ActiveRecord::Base.connection.disconnect!
        end
        after_fork do |server, worker|
          Signal.trap ‘TERM’ do
            puts ‘Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT’
          end
          defined?(ActiveRecord::Base) and
            ActiveRecord::Base.establish_connection
        end

        
Step 10:- Next, we need to tell Nginx how to talk to Unicorn. For this purpose, it is sufficient at this level to edit the default configuration file: default.conf and leave nginx.conf as provided — which is already set to include the default configurations.

   $ nano /etc/nginx/conf.d/default.con

   
Replace the files contents with the ones from below, again amending the necessary bits to suit your needs:

        upstream app {
          # Path to Unicorn SOCK file, as defined previously
          server unix:/tmp/unicorn.myapp.sock fail_timeout=0;
        }
        server {
            listen 80;
            server_name localhost;
            # Application root, as defined previously
            root /root/my_app/public;
            try_files $uri/index.html $uri @app;
            location @app {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_redirect off;
                proxy_pass http://app;
            }
            error_page 500 502 503 504 /500.html;
            client_max_body_size 4G;
            keepalive_timeout 10;
        }  

        
Save and exit by pressing CTRL+X and confirming with Y.
  

Step 11:- Managing The Servers

# Make sure that you are inside the application directory
Once you setup you server, start your rails server in production mode with unicorn

   $ unicorn -c config/unicorn.rb -D -E production
   $ service nginx restart

Share this Article