Monday, 28 January 2019

How to Deploy Rails Application using Nginx with Unicorn

Steps for Unicorn & Nginx Deployment in Rails

Unicorn Configuration

1. Add unicorn in gem file
gem 'unicorn'

2. Create new file in config folder
$ vim config/unicorn.rb

Paste the below codes in unicorn.rb file
# set path to application
app_dir = File.expand_path("../..", __FILE__)
shared_dir = "#{app_dir}/shared"
working_directory app_dir


# Set unicorn options
worker_processes 2
preload_app true
timeout 30

# Set up socket location
listen "#{shared_dir}/sockets/unicorn.sock", :backlog => 64

# Logging
stderr_path "#{shared_dir}/log/unicorn.stderr.log"
stdout_path "#{shared_dir}/log/unicorn.stdout.log"

# Set master PID location
pid "#{shared_dir}/pids/unicorn.pid"

3. Create the folder were referred in unicorn.rb files
$  mkdir -p shared/pids shared/sockets shared/log



Unicorn init script setup

1. Create init script file

$  sudo vim /etc/init.d/unicorn_serversetup

2. Paste the below script in unicorn_serversetup file

#!/bin/sh
### BEGIN INIT INFO
# Provides:          unicorn
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the unicorn app server
# Description:       starts unicorn using start-stop-daemon
### END INIT INFO

set -e

USAGE="Usage: $0 <start|stop|restart|upgrade|rotate|force-stop>"

# app settings
USER="rajkumar"
APP_NAME="/Rajkumar/Projects/serversetup"
APP_ROOT="/home/$USER/$APP_NAME"
ENV="production"

# environment settings
PATH="/home/$USER/.rbenv/shims:/home/$USER/.rbenv/bin:$PATH"
CMD="cd $APP_ROOT && bundle exec unicorn -c config/unicorn.rb -E $ENV -D"
PID="$APP_ROOT/shared/pids/unicorn.pid"
OLD_PID="$PID.oldbin"

# make sure the app exists
cd $APP_ROOT || exit 1

sig () {
  test -s "$PID" && kill -$1 `cat $PID`
}

oldsig () {
  test -s $OLD_PID && kill -$1 `cat $OLD_PID`
}

case $1 in
  start)
    sig 0 && echo >&2 "Already running" && exit 0
    echo "Starting $APP_NAME"
    su - $USER -c "$CMD"
    ;;
  stop)
    echo "Stopping $APP_NAME"
    sig QUIT && exit 0
    echo >&2 "Not running"
    ;;
  force-stop)
    echo "Force stopping $APP_NAME"
    sig TERM && exit 0
    echo >&2 "Not running"
    ;;
  restart|reload|upgrade)
    sig USR2 && echo "reloaded $APP_NAME" && exit 0
    echo >&2 "Couldn't reload, starting '$CMD' instead"
    $CMD
    ;;
  rotate)
    sig USR1 && echo rotated logs OK && exit 0
    echo >&2 "Couldn't rotate logs" && exit 1
    ;;
  *)
    echo >&2 $USAGE
    exit 1
    ;;
esac


3. Give user name and app name and save the files

4. Update the script's permissions and enable Unicorn to start on boot:

  $ sudo chmod 755 /etc/init.d/unicorn_serversetup
  $  sudo update-rc.d unicorn_serversetup defaults 

5. start the unicorn 

  $  sudo service unicorn_serversetup start

6. Your application will run shared/sockets/unicorn.sock 


Install and Configure Nginx

1. $ sudo apt-get install nginx

2. $ sudo vi /etc/nginx/sites-available/default

3. configure below items

upstream app {
    # Path to Unicorn SOCK file, as defined previously
    server unix:/home/deploy/appname/shared/sockets/unicorn.sock fail_timeout=0;
}

server {
    listen 80;
    server_name localhost;

    root /home/deploy/appname/public;

    try_files $uri/index.html $uri @app;

    location @app {
        proxy_pass http://app;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
    }

    error_page 500 502 503 504 /500.html;
    client_max_body_size 4G;
    keepalive_timeout 10;
}

4. $ sudo service nginx restart

5. Any 403 error you can check the sudo /var/log/nginx/error.log





Monday, 31 December 2018

Export and Import options for Mysql & Postgresql Databases

DataBase Dump & Restore for MYSQL
 
Take dump from database or Export from database

   Terminal : mysqldump -h localhost --user test --password testing > testingdb.sql

Import dump files to Database or Import

  Terminal : mysql -u root -p testing_new < testingdb.sql


DataBase Dump & Restore for POSTGRESQL
 
Take dump from database or Export 

  Terminal : pg_dump -h localhost -U postgres -d testing > testdb.sql

Import dump files to Database or Import
 
  Terminal : psql -h localhost -U postgres -d testing_new < testdb.sql

Thursday, 28 June 2018

SMS integration using msg91 in ruby

require 'uri'
require 'net/http'

PARAMS

sender = 'RAJKMAR'
route = 4
mobiles = '91********'
authkey = '**********'
message = 'Your message'
country = '91'

API CALL:

url = URI("http://api.msg91.com/api/sendhttp.php?sender=#{sender}&route=#{route}&mobiles=#{mobiles}&authkey=#{authkey}&encrypt=&country=#{country}&message=#{message}")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Get.new(url)

response = http.request(request)

Friday, 15 June 2018

Deploy rails application with nginx and unicorn server configurations

NGNIX SETUP With Rails Application
==================================
1. sudo apt-get install nginx

2. sudo vi /etc/nginx/sites-enabled/default -> Open config file

3.Update the below changes in nginx default file

root /home/rajkumar/Rajkumar/Projects/rajuthayaa
server_name localhost;
location @raj{
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://localhost:3001;
}

4. sudo service nginx start

5. if any errors in nginx kindly run the below command and check it.
 sudo vi /var/log/nginx/error.log



UNICORN SETUP With Rails Application
====================================
1. gem 'unicorn' in your gemfiles

2. create unicorn.rb in config/unicorn.rb

3. Update the below changes in unicorn.rb files

APP_PATH = "/home/rajkumar/Rajkumar/Projects/rajuthayaa"

working_directory APP_PATH
stderr_path APP_PATH + "/log/unicorn.stderr.log"
stdout_path APP_PATH + "/log/unicorn.stdout.log"

preload_app true

timeout 30

listen "/home/rajkumar/Rajkumar/Projects/rajuthayaa/shared/sockets/unicorn.rajutaya.sock", :backlog => 64

listen 3002, :tcp_nopush => true

pid  APP_PATH + "/unicorn.pid"

before_fork do |server, worker|
  defined?(ActiveRecord::Base) and
      ActiveRecord::Base.connection.disconnect!
end

after_fork do |server, worker|
  defined?(ActiveRecord::Base) and
      ActiveRecord::Base.establish_connection
end

upstream raj(raj){
server unix:/home/rajkumar/Rajkumar/Projects/rajuthayaa/shared/sockets/unicorn.rajutaya.sock fail_timeout=0;
}

4. Add upstream in nginx config files -->sudo vi /etc/nginx/sites-enabled/default

upstream raj(raj){
server unix:/home/rajkumar/Rajkumar/Projects/rajuthayaa/shared/sockets/unicorn.rajutaya.sock fail_timeout=0;
}

5. create shared/sockets inside your rails app

6. unicorn_rails -c config/unicorn.rb -D for run the unicorn server.

7. if any issues kindly check the log/unicorn.stderr.log files.

8. Restart both nginx and unicorn server it will work.

Wednesday, 6 June 2018

Unix setup in rails application

Unicorn setup for deployment

1. gem 'unicorn' add in gem file

2. create config/unicorn.rb file

3. paste this file
# set path to application
app_dir = File.expand_path("../..", __FILE__)
shared_dir = "#{app_dir}/shared"
working_directory app_dir


# Set unicorn options
worker_processes 2
preload_app true
timeout 30

# Set up socket location
listen "#{shared_dir}/sockets/unicorn.sock", :backlog => 64

# Logging
stderr_path "#{shared_dir}/log/unicorn.stderr.log"
stdout_path "#{shared_dir}/log/unicorn.stdout.log"

# Set master PID location
pid "#{shared_dir}/pids/unicorn.pid"

4. mkdir -p shared/pids shared/sockets shared/log

5. create script in /etc/init.d/unicorn_appname

6. sudo chmod 755 /etc/init.d/unicorn_appname

7. sudo update-rc.d unicorn_appname defaults

8. sudo service unicorn_appname start

Sunday, 29 September 2013

Message chat for rails using ajax

In message controller.rb


class MessagesController < ApplicationController
  # GET /messages
  def index
   @messages=Message.all
    @raj=Message.new
  end

  def create
    @message = Message.create!(params[:message])
  end
end

In messages/index.html

<h2>Chat</h2>

<ul style="background-color:#aaaaaa;width: 100px;border:1px solid blueviolet;" id="chat">
  <%= render :partial => @messages%>
</ul>

<div id="message_form">
<%= form_for(@raj, :remote=>true) do |f| %>
  <div class="field">
    <%= f.text_field :content %>
  </div>
  <div class="actions">
    <%= f.submit 'Send' %>
  </div>
<% end %>
</div>

In messages/_message.html.erb

<%= content_tag_for(:li, message) do %>
  <%= message.content %>
<% end %>

In messages/create.js.erb

$('#chat').append('<%= escape_javascript(render(@message)) %>');
$("#message_form")[0].reset();

Friday, 12 October 2012

Devise Details

Devise usages for rails 3 application:

Devise is very simple authentication solution for Rails 3 application.
There are many gems for authenticating a rails application. But, "devise" is the gem which will make authentication of a rails 3 application easier.

1) Include devise gem in Gemfile as following,

gem ‘devise’

2)Run the below command

bundle install

3) Run generator as following,

rails g devise:install

4) Create model ‘User’ to store authentication

rails g devise User

5)To make the view files we have to give the following command

rails g devise:views

6)For database creation

rake db:create
rake db:migration

7)In layouts applicaiton.html.erb:

<div id="user_nav">
<% if user_signed_in? %>
Signed in as <%= current_user.email %>. Not you?
<%= link_to "Sign out", destroy_user_session_path %>
<% else %>
<%= link_to "Sign up", new_user_registration_path %> or <%= link_to "sign in", new_user_session_path %>
<% end %>
</div>


And also add the following code to the same html file in body tag:

<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>

8) Add the following code to the "config/environments/development.rb" file:

config.action_mailer.default_url_options = { :host => 'localhost:3000' }

9) Now we can create our own controller which, we need this authentication.

rails g controller home

10) if we want to authenticate this controller’s action means we have to give like this,

before_filter :authenticate_user!

11) In routes,(config/routes.rb)

root :to => "home#index"

Whenever you enter the home controller action in url means it will authenticate.

References:
https://github.com/plataformatec/devise
http://www.rorexperts.com/authentication-of-rails-3-application-using-devise-gem-t2243.html
http://www.allerin.com/blog/devise-usage-in-rails-3-devise-authentication-in-ruby-on-rails-3-application/


Omniauth gem for facebook and twitter integration:

1.In gem files
gem 'omniauth'

2.bundle install
rails g scaffold authentication user_id:integer provider:string uid:string index create destroy
rake db:migrate


3.models/user.rb
has_many :authentications

4.models/authentications.rb
belongs_to :user

5.config/routes.rb

match '/auth/:provider/callback' => 'authentications#create'
6.authentications_controller.rb

def index
 @authentications = current_user.authentications if current_user
end

def create
 auth = request.env["rack.auth"]
 current_user.authentications.find_or_create_by_provider_and_uid(auth['provider'], auth['uid'])
 flash[:notice] = "Authentication successful."
 redirect_to authentications_url
end

def destroy
 @authentication = current_user.authentications.find(params[:id])
 @authentication.destroy
 flash[:notice] = "Successfully destroyed authentication."
 redirect_to authentications_url
end


7.config/initializers/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
 provider :twitter, 'CONSUMER_KEY', 'CONSUMER_SECRET'

 provider :facebook, 'APP_ID', 'APP_SECRET'
 #provider :linked_in, 'CONSUMER_KEY', 'CONSUMER_SECRET'
end


8.authentications/index.html.erb

<% title "Sign In" %>

<% if @authentications %>
 <% unless @authentications.empty? %>
   <p><strong>You can sign in to this account using:</strong></p>
   <div class="authentications">
     <% for authentication in @authentications %>
       <div class="authentication">
         <%= image_tag "#{authentication.provider}_32.png", :size => "32x32" %>
         <div class="provider"><%= authentication.provider.titleize %></div>
         <div class="uid"><%= authentication.uid %></div>
         <%= link_to "X", authentication, :confirm => 'Are you sure you want to remove this authentication option?', :method => :delete, :class => "remove" %>
       </div>
     <% end %>
     <div class="clear"></div>
   </div>
 <% end %>
 <p><strong>Add another service to sign in with:</strong></p>
<% else %>
 <p><strong>Sign in through one of these services:</strong></p>
<% end %>

<a href="/auth/twitter" class="auth_provider">
 <%= image_tag "twitter_64.png", :size => "64x64", :alt => "Twitter" %>
 Twitter
</a>
<a href="/auth/facebook" class="auth_provider">
 <%= image_tag "facebook_64.png", :size => "64x64", :alt => "Facebook" %>
 Facebook
</a>
<div class="clear"></div>


9.For stylesheets (application.css)

.authentications {
 margin-bottom: 30px;
}
.authentication {
 width: 130px;
 float: left;
 background-color: #EEE;
 border: solid 1px #999;
 padding: 5px 10px;
 -moz-border-radius: 8px;
 -webkit-border-radius: 8px;
 position: relative;
 margin-right: 10px;
}
.authentication .remove {
 text-decoration: none;
 position: absolute;
 top: 3px;
 right: 3px;
 color: #333;
 padding: 2px 4px;
 font-size: 10px;
}
.authentication .remove:hover {
 color: #CCC;
 background-color: #777;
 -moz-border-radius: 6px;
 -webkit-border-radius: 6px;
}
.authentication img {
 float: left;
 margin-right: 10px;
}
.authentication .provider {
 font-weight: bold;
}

.authentication .uid {
 color: #666;
 font-size: 11px;
}
.auth_provider img {
 display: block;
}
.auth_provider {
 float: left;
 text-decoration: none;
 margin-right: 20px;
 text-align: center;
 margin-bottom: 10px;
}


Reference link:

screenshot details:
http://railscasts.com/episodes/235-omniauth-part-1

http://stackoverflow.com/questions/11093120/devise-omniauth-and-facebook-integration-session-error

http://www.phyowaiwin.com/how-to-download-and-display-twitter-feeds-for-new-year-resolution-using-ruby-on-rails

http://railscasts.com/episodes/235-omniauth-part-1

Interactor in Rails

What is interactor? Interactor provides a common interface for performing complex user interactions An interactor is a simple, sin...