Setup apache, passenger, ruby on rails on Ubuntu RACKSPACE with mysql database

Hi , I am going write about setup of apache, passenger and ruby on rails on Ubuntu rackspace.
I am going to use MySQL as a database.

Generate SSH keys from your local machine

hareror@hareram-u11:~/>ssh-keygen -t rsa -C "your@email.com"

#Generating public/private rsa key pair.
#Enter file in which to save the key (/home/hareror/.ssh/id_rsa):
hareror@hareram-u11:~/>[hit enter]

#Enter passphrase (empty for no passphrase):

hareror@hareram-u11:~/>[enter a passphrase]
#Enter same passphrase again:
hareror@hareram-u11:~/>[enter passphrase again]

Update and upgrade the RACKSPACE Server

For updating and upgrading the RACKSPACE server you need to access the server by SSH.
You can use the below command to access the server and replace xxx.xxx.xxx.xxx with your RACKSAPCE server IPv4 address. You can get it from your RACKSPACE admin control panel.

  
hareror@hareram-u11:~/> ssh root@xxx.xxx.xxx.xxx

Run the below command for updating & upgrading the server package and os of the Ubuntu server.

root@servername:~# apt-get update

root@servername:~# apt-get upgrade

Creat User and setup SSH keys on Sever

We need to create a new user on RACKSPACE server for deployment of RoR Application.
For creating a new user use the below command and provide the information required after running the command

root@servername:~# adduser deploy

Now create a .ssh directory inside the “/home/deploy/” and changed it’s permission using the below command.

root@servername:~# mkdir /home/deploy/.ssh
root@servername:~# chmod 700 /home/deploy/.ssh

We have to upload the public ssh key of your local machine to RACKSPACE server. So that we don’t have to enter password at every time. For doing this we have to a file “/home/deploy/.ssh/authorized_keys” and copy the content of “/.ssh/id_rsa.pub” and paste in the file “/home/deploy/.ssh/authorized_keys”. For doing this you can any editor like “nano”.

Now we have to set the permissions and ownerships for the user’s keys and home directory.

root@servername:~# chmod 400 /home/deploy/.ssh/authorized_keys
root@servername:~# chown deploy:deploy /home/deploy -R

Also we have to grant sudo privileges to the deploy user.To grant the privileges, edit the file “/etc/sudoers”. Actually we have to add the below line to grant the privileges.

deploy  ALL=(ALL) ALL

Now restrat the ssh service using the below command.

root@servername:~# service ssh restart

Install Some Ubuntu Packages

Before installing the Ruby and Rails we need to install some Ubuntu packages.Use the below command for installing these packages.

root@servername:~# sudo apt-get install curl git-core build-essential zlib1g-dev libssl-dev libreadline-gplv2-dev libyaml-dev libcurl4-openssl-dev

Now we are ready to install Ruby using wget command. We are creating the directory named
“downloads” inside deploy directory for keeping the source file of ruby.


root@servername:~# mkdir downloads && cd downloads
root@servername:~/downloads# wget ftp://ftp.ruby-lang.org/pub/ruby/2.0/ruby-2.0.0-p247.tar.gz
root@servername:~/downloads# tar -zxf ruby-2.0.0-p247.tar.gz
root@servername:~/downloads# cd ruby-2.0.0-p247
root@servername:~/downloads/ruby-2.0.0-p247# ./configure
root@servername:~/downloads/ruby-2.0.0-p247# make
root@servername:~/downloads/ruby-2.0.0-p247# sudo make install

Now we can install rubygem using the below commands for managing the gems.


root@servername:~/downloads# wget http://production.cf.rubygems.org/rubygems/rubygems-2.0.6.tgz
root@servername:~/downloads# tar -zxf rubygems-2.0.6.tgz
root@servername:~/downloads# cd rubygems-2.0.6
root@servername:~/downloads/rubygems-2.0.6# sudo ruby setup.rb 

Then, create ~/.bashrc and add the line in the file.

export PATH=$PATH:/usr/local/lib/ruby/gems/2.0.0

Now we need to install bundler and rake gem using the below commands.

root@servername:~# sudo gem install bundler
root@servername:~# sudo gem install rake

Setup MySQL on RACKSPACE

We can install MySQL server by using this command

root@servername:~# sudo apt-get install mysql-server

Then follow the message shown by mysql and finally it will asked for password and repeat password.Give same the password for both.
Now the MySQL server is installed. You can checkout by running below command

  root@servername:~#  mysql -u root -p

Then we need to install a package to use the mysql2 gem .

root@servername:~#sudo apt-get install libmysqlclient15-dev

It will be better to create a new database user for using this credential in RoR application.
First login to Mysql as root then use the below command to create a user.

mysql> GRANT ALL PRIVILEGES ON *.* TO 'deploy'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;

It will create a new user with name “deploy” and password as “password”. So we can now use it in database.yml file.

Install Apache2 with Passenger

We are going to use apache2 as a web server. So use the below command for installing it.

 
root@servername:~# sudo aptitude install apache2 apache2.2-common apache2-mpm-prefork apache2-utils libexpat1 ssl-cert

Then go for configuring the apache with passenger and install the passenger gem.

 
root@servername:~# sudo gem install passenger

Now compile the Phusion Passenger binaries, which include the various Phusion Passenger agent executables and the Phusion Passenger Apache module.

root@servername:~# sudo passenger-install-apache2-module

Now we got the below output.

The Apache 2 module was successfully installed.

Please edit your Apache configuration file, and add these lines:

LoadModule passenger_module /usr/local/lib/ruby/gems/1.9.1/gems/passenger-4.0.10/buildout/apache2/mod_passenger.so
PassengerRoot /usr/local/lib/ruby/gems/1.9.1/gems/passenger-4.0.10
PassengerDefaultRuby /usr/local/bin/ruby

After you restart Apache, you are ready to deploy any number of Ruby on Rails
applications on Apache, without any further Ruby on Rails-specific
configuration!

Now add the above lines in “/etc/apache2/apache2.conf” file.

Now we are ready to setup virtual host and we need to create a virtual host so that apache can handle the requests and pass off to passenger.

Now create a file /etc/apache2/sites-available/192.20.20.243 with the following contents.

<VirtualHost *:80>
      ServerName 192.20.20.243
      # !!! Be sure to point DocumentRoot to 'public'!
      DocumentRoot /var/www/192.20.20.243/current/public   
      <Directory /somewhere/public>
         # This relaxes Apache security settings.
         AllowOverride all
         # MultiViews must be turned off.
         Options -MultiViews
      </Directory>
</VirtualHost>

Now the enable the site “192.20.20.243” using below one

 sudo a2ensite 192.20.20.243
 sudo /etc/init.d/apache2 reload
 sudo chown www-data:www-data /var/www
 sudo chmod g+w /var/www

Now capify your any existing Rails application and change the deploy.rb file like the below as a sample code. Please change the git application with yours git repo application.


require 'bundler/capistrano'

set :application, "demoapp"

default_run_options[:pty] = true
set :ssh_options, { :forward_agent => true }

set :repository,  "git@github.com:hareramrai/demoapp.git"
set :scm, :git
set :scm_username, "hareramrai"
set :branch, "master"
set :git_enable_submodules, 1
set :rails_env, "production"
set :deploy_to, "/var/www/#{application}"
set :deploy_via, :remote_cache

set :user, "deploy"
set :use_sudo, false

role :web, "192.20.20.243"                      # Your HTTP server, Apache/etc
role :app, "192.20.20.243"                      # This may be the same as your `Web` server
role :db,  "192.20.20.243", :primary => true    # This is where Rails migrations will run

# if you want to clean up old releases on each deploy uncomment this:
after "deploy:restart", "deploy:cleanup"

namespace :deploy do
  task :start, :roles => :app do
    run "touch #{current_path}/tmp/restart.txt"
  end

  task :stop, :roles => :app do
    # Do nothing.
  end

  desc "Restart Application"
  task :restart, :roles => :app do
    run "touch #{current_path}/tmp/restart.txt"
  end

  after 'deploy:update_code' do
    run "cd #{release_path}; RAILS_ENV=production rake db:create"
    run "cd #{release_path}; RAILS_ENV=production rake db:migrate"
    run "cd #{release_path}; RAILS_ENV=production rake db:seed"
    run "cd #{release_path}; RAILS_ENV=production rake assets:precompile"
  end

end

Now we are ready for capistrano setup for that run the below command :

 cap deploy:setup 

Now deploy the application using this

 cap deploy 

Now we can check the own currently deployed application at “https://192.20.20.243 “. This URL is an sample URL please change it with your URL.

Setup production server with apache, passenger and SSL in ruby on rails

Hi
Today I am going to setup production server in my local machine with Apache,Passenger server using Capistrano.Also going to use SSL with Apache.

Now we are going to create simple scaffold-ed application using ruby on rails. Which only has a single table users and it stores the simple user data. Now Create “deploy_demo_app” by running the below command

 hareror@hareram-u11:~/Projects/RubyOnRails/GitHub$ rails new deploy_demo_app -d mysql

 hareror@hareram-u11:~/Projects/RubyOnRails/GitHub$ cd deploy_demo_app && echo "rvm gemset use deploy_demo_app" >.rvmrc

 hareror@hareram-u11:~/Projects/RubyOnRails/GitHub/deploy_demo_app$rails g scaffold user name:string email:string date_of_birth:date

 hareror@hareram-u11:~/Projects/RubyOnRails/GitHub/deploy_demo_app$ rake db:create

 hareror@hareram-u11:~/Projects/RubyOnRails/GitHub/deploy_demo_app$ rake db:migrate

Now initialize the application using git because we are using git as a scm. Then the run the below command to initialize the git git repository.

 hareror@hareram-u11:~/Projects/RubyOnRails/GitHub/deploy_demo_app$ git init .

Also add the these two “rvm-capistrano” and “capistrano” gems to Gemfile.Then the capify the application using below one

 
 hareror@hareram-u11:~/Projects/RubyOnRails/GitHub/deploy_demo_app$ capify .

Then go for configuring the apache with passenger and install the passenger gem.

 
 hareror@hareram-u11:~/Projects/RubyOnRails/GitHub/deploy_demo_app$ gem install passenger

Now compile the Phusion Passenger binaries, which include the various Phusion Passenger agent executables and the Phusion Passenger Apache module.

hareror@hareram-u11:~/Projects/RubyOnRails/GitHub/deploy_demo_app$ passenger-install-apache2-module

Now we got the below output.

 --------------------------------------------
The Apache 2 module was successfully installed.
Please edit your Apache configuration file, and add these lines:
LoadModule passenger_module /home/hareror/.rvm/gems/ruby-1.9.3-p327@deploy_demo_app/gems/passenger-3.0.19/ext/apache2/mod_passenger.so
PassengerRoot /home/hareror/.rvm/gems/ruby-1.9.3-p327@deploy_demo_app/gems/passenger-3.0.19
PassengerRuby /home/hareror/.rvm/wrappers/ruby-1.9.3-p327@deploy_demo_app/ruby

Now add the first line in ” /etc/apache2/mods-available/passenger.load” file and last two line in “/etc/apache2/mods-available/passenger.conf”.
Now we are ready to setup virtual host and we need to create a virtual host so that apache can handle the requests and pass off to passenger.

Now create a file /etc/apache2/sites-available/192.168.9.247 with the following contents within ” <VirtualHost *:443> </VirtualHost> “:

  ServerName 192.168.9.247
  DocumentRoot /var/www/192.168.9.247/current/public
      # This relaxes Apache security settings.
      AllowOverride all
      # MultiViews must be turned off.
      Options -MultiViews
  SSLEngine on
  SSLCertificateFile /etc/ssl/certs/server.crt
  SSLCertificateKeyFile  /etc/ssl/private/server.key

The server.crt and server.key files are used for SSL setup.
Now the enable the site “192.168.9.247” using below one

 sudo a2ensite 192.168.9.247
 sudo /etc/init.d/apache2 reload
 sudo chown www-data:www-data /var/www
 sudo chmod g+w /var/www

Now to back rails app and change the “deploy.rb” file with below contents:

require 'rvm/capistrano'
set :rvm_type, :user
set :rvm_ruby_string, 'ruby-1.9.3-p327@deploy_demo_app'
set :application, "192.168.9.247"
set :repository,  "git://github.com/Hareramrai/deploy_demo_app.git"
set :scm, :git 
set :scm_username, "hareramrai"
set :branch, "master"
set :git_enable_submodules, 1
set :rails_env, "production"
default_environment["RAILS_ENV"] = 'production'
#set :rake , "/usr/bin/env/rake"
set :deploy_to, "/var/www/192.168.9.247"
set :deploy_via, :remote_cache
set :user, "hareror"
set :use_sudo, false
role :web, "192.168.9.247"                          # Your HTTP server, Apache/etc
role :app, "192.168.9.247"                          # This may be the same as your `Web` server
role :db,  "192.168.9.247", :primary =>; true        # This is where Rails migrations will run
role :db,  "192.168.9.247"

# if you want to clean up old releases on each deploy uncomment this:
after "deploy:restart", "deploy:cleanup"

# if you're still using the script/reaper helper you will need
# these http://github.com/rails/irs_process_scripts

# If you are using Passenger mod_rails uncomment this:
 namespace :rvm do
   task :trust_rvmrc do
     run "rvm rvmrc trust #{release_path}"
   end
 end

 namespace :deploy do
  task :start, :roles => :app do
    run "touch #{current_path}/tmp/restart.txt"
  end

  task :stop, :roles => :app do
    # Do nothing.
  end

  desc "Restart Application"
  task :restart, :roles => :app do
    run "touch #{current_path}/tmp/restart.txt"
  end

  after "deploy", "rvm:trust_rvmrc"
  #  after "deploy:update_code", "deploy:migrate"
  after 'deploy:update_code' do
    run "cd #{release_path}; RAILS_ENV=production rake assets:precompile"
    run "cd #{release_path}; RAILS_ENV=production rake db:create"
    run "cd #{release_path}; RAILS_ENV=production rake db:migrate"
  end

 end

Now update the code at github.

 git add . && git commit -m "initial commit"
 git remote add origin git@github.com:Hareramrai/deploy_demo_app.git
 git pull origin master
 git push origin master

Now create the certificates for SSL. We are going the create Self-Signed Certificate.
First Generating a Certificate Signing Request (CSR) using below commands:

openssl genrsa -out server.key 1024
openssl req -new -key server.key -out server.csr

To create the self-signed certificate, run the following command at a terminal prompt:

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

You have to install the key file server.key and certificate file server.crt for that use the below commands:

sudo cp server.crt /etc/ssl/certs
sudo cp server.key /etc/ssl/private 

Now we are ready for capistrano setup for that run the below command :

 cap deploy:setup 

Now deploy the application using this

 cap deploy 

Now we can check the own currently deployed application at “https://192.168.9.247 “.

You can checkout my github application at https://github.com/Hareramrai/deploy_demo_app

Thanks for reading the post 🙂 ………
Please put your queries below if you have any?

Currency Converter in Ruby on Rails

We can convert money from a currency unit to another currency unit using a web service provided by websericex.net.
The conversion rate is very volatile , so we have to depend on a good resource and websericex.net is not only a good resource but also a free service to use.

I have already written a tips about it at mindfire solutions tips section.

You can checkout the details at currency converter

You can also checkout my running application at heroku and github source code at https://github.com/Hareramrai/CurrencyConverter

Please put your queries below if you have any?

Thanks for reading the post 🙂 ………..

Setup Ruby on Rails on ubuntu 12.04 with mysql database

Hi
Today I am going to install ruby on rails with mysql database on Ubuntu 12.04.

We can install MySQL server by using this command

hareram@hareram:~$ sudo apt-get install mysql-server

Then follow the message shown by mysql and finally it will asked for password and repeat password.Give same the password for both.
Now the MySQL server is installed. You can checkout by running below command

  hareram@hareram:~$  mysql -u root -p

Now check if your system has already installed curl or not by running the below command.

  hareram@hareram:~$ curl

If you see the below one then curl is not installed on your system.

The program 'curl' is currently not installed.  You can install it by typing:
sudo apt-get install curl

Then install curl on your system using the below command

   hareram@hareram:~$ sudo apt-get install curl

We are installing the curl because we need to install rvm using curl.

Now we are ready to install rvm .
We can install rvm using the below command

  hareram@hareram:~$\curl -L https://get.rvm.io | bash -s stable

If you will get warning like below one

  * WARNING: You're using ~/.profile, make sure you load it,
    add the following line to ~/.bash_profile if it exists
    otherwise add it to ~/.bash_login:

      source ~/.profile

Then add “source ~/.profile” to bash_profile file.
Also run the below command

  hareram@hareram:~$ echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # Load RVM function' >> ~/.bashrc

Now check the requirements for installing ruby using below command

   hareram@hareram:~$ rvm requirements

After running the above command you will get the additional list of application need to be installed before ruby is installed

# For ruby:
sudo apt-get --no-install-recommends install build-essential openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev libgdbm-dev ncurses-dev automake libtool bison subversion pkg-config libffi-dev

Run the above command to install the other application before installing the ruby.

Now we can install the ruby 1.9.3 using the below command

  hareram@hareram:~$ rvm install 1.9.3

Now the set default ruby using

 hareram@hareram:~$ rvm use 1.9.3 --default

Now install current version rails using the below command

  hareram@hareram:~$ gem install rails 

Now creata a demoapp using rails

  hareram@hareram:~$ rails new demoapp -d mysql

We have passed “-d mysql” for using mysql database for application.
If you get the below error of mysql2 gem install

 An error occurred while installing mysql2 (0.3.11), and Bundler cannot continue.
 Make sure that `gem install mysql2 -v '0.3.11'` succeeds before bundling.

Then you have to install the below application to complete the mysql2 gem installation.

 sudo apt-get install libmysql-ruby
 sudo apt-get install libmysqlclient-dev

Now Ruby on Rails with mysql database are installed on your system and you are ready to fly in the world of Ruby on Rails.
Thanks for reading post ….. 🙂
Please put your queries if you have any?

How to use private_pub gem on heroku in ruby on rails

In this post I am going to show how to use private_pub gem on heroku. Before going to use it we have to setup private_pub server on heroku. Use this link to setup the server.

Private Pub gem is a very nice solution for pushing real time data and it’s open-source . Now create a rails app using “rails new demo_private_pub”. Then we have to add the gems given below

gem ‘private_pub’
gem ‘thin’

After adding the gem bundle it. Then use this “rails g private_pub:install” to create private_pub settings files. It will create two file “config/private_pub.yml” and “private_pub.ru”. We have to change the content of private_pub.yml to below one

production:
secret_token: “batkaro”
signature_expiration: 86400 # one day

We got “server: http://fayeserver.herokuapp.com/faye ” from private_pub server setup. Because private pub is running on this server.

Then we have to move file “private_pub.ru” inside “config / initializers” of application.
After that remove the “run PrivatePub.faye_app” from “private_pub.ru”.

Now we are ready use to private_pub.

Add this “//= require private_pub” to applications.js file.

<%= subscribe_to "/messages/new" %>  # use this for subscribing to a channel

<% publish_to "/messages/new" do %> # use this for publishing the data to a channel.
  $("#post-list-div").append("<%= j render(@post) %>");
<% end %>

You can checkout my live chat application at http://batkaro.herokuapp.com
Also you can checkout my github code at https://github.com/Hareramrai/batkaro

Image Uploading to facebook and tagging friends

For uploading and tagging the friends on Facebook in Ruby on Rails , we need a gem named “fb-graph”. Which will provide the api call for this functionality.

# @Params : params
# @Return : None
# @Purpose : To tag user on the image with comment and upload it to facebook
def create

# find the image from the image_id
@image = Image.find_by_id(params[:image_id])

# fetch the user details from the facebook
me = FbGraph::User.me(current_user.auth_token)

#create the array of friends uid

friends = params[:friends].split(",")

tags = []

# looping through friends array

friends.each do |friend|

#creating a new tag object and add it to tag array

tags << FbGraph::Tag.new(
:id => friend,
:name => "with Facebook profile link",
: x => 2*Random.rand(9),
:y => 9*Random.rand(2)
)

end # end of friends block

# uploading the image the friends tag
FbGraph::User.me(current_user.auth_token).photo!(
:url => @image.picture.url ,
:message => params[:message],
:tags => tags
)

flash[:success] = "Successfully uploaded and tagged the your friends."

redirect_to image_path(@image)

end # end of create action

Also you can pass the source file to upload the image instead of image url using
FbGraph::User.me(ACCESS_TOKEN).photo!(
:source => File.new(File.join(File.dirname(__FILE__), 'fb_graph.png'), 'rb'),
:message => params[:message],
:tags => tags
)


For more information visit the site https://github.com/nov/fb_graph/

Also you can checkout my running application at http://warm-badlands-9447.herokuapp.com
Thanks for reading the post……. 🙂

Authorization with dropbox in Ruby on Rails using dropbox-sdk

For Dropbox authorization we have a nice ruby gem “dropbox-sdk”. Which will provide a nice interface through which we can call the dropbox api in ruby on rails.

we have to create a dropbox application at https://www.dropbox.com/developers/apps.

You have to fill up a form to create an application , below is a sample data for the form

App Type : Core API
App Name: ImageUploader
Description:  Sample  application for image uploading.
Access:  Full Dropbox

After submitting the form you will get  App Key and App secret.

Add gem “dropbox-sdk” in Gemfile and bundle it.

Then create a file dropbox_config.rb in side the “application_name/config/initializer/”.

Add the below data  to dropbox_config.rb file and change the “XXXXXXX” with your app data .

# Get your app key and secret from the Dropbox developer website
DROPBOX_APP_KEY = "XXXXXXXXX"
DROPBOX_APP_KEY_SECRET = "XXXXXXXXX"
DROPBOX_APP_MODE = "dropbox" # if you have a single-directory app or "dropbox" if it has access to the whole dropbox

Now create the controller , here the name of the controller is “users” and the code for it is given below:-

class UsersController < ApplicationController

# @Params : None
# @Return : None
# @Purpose : To create new dropbox session for authorization
def authorize

dbsession = DropboxSession.new(DROPBOX_APP_KEY, DROPBOX_APP_KEY_SECRET)
#serialize and save this DropboxSession
session[:dropbox_session] = dbsession.serialize
#pass to get_authorize_url a callback url that will return the user here
redirect_to dbsession.get_authorize_url url_for(:action => 'dropbox_callback')

end

# @Params : None
# @Return : None
# @Purpose : To callback for dropbox authorization
def dropbox_callback

dbsession = DropboxSession.deserialize(session[:dropbox_session])
dbsession.get_access_token #we've been authorized, so now request an access_token
session[:dropbox_session] = dbsession.serialize
current_user.update_attributes(:dropbox_session => session[:dropbox_session])
session.delete :dropbox_session
flash[:success] = "You have successfully authorized with dropbox."

redirect_to root_path

end # end of dropbox_callback action

end # end of class

Now we are ready to do any thing that is possible with dropbox(eg:- upload ,  download ).

Lets try to upload a file to dropbox the code for it is below
dbsession = DropboxSession.deserialize(current_user.dropbox_session)
# create the dropbox client object
client = DropboxClient.new(dbsession, DROPBOX_APP_MODE)
data = File.read("/path/to/test.png")
client.put_file("test.png",data)

thanks for reading .

You can checkout my sample application at http://warm-badlands-9447.herokuapp.com/