Wednesday, October 28, 2015

Redirect rules for nginx server block

If you want server_name without www then follow this
server {
 listen 80 default_server;
 server_name subdomain.domain.com;
 passenger_enabled on;
 passenger_app_env production;
 root /home/sachin/testapp/public;
}
server {
listen 80;
server_name www.subdomain.domain.com;
return 301 $scheme://subdomain.domain.com$request_uri;
}
If you want server_name with www then follow this
server {
 listen 80 default_server;
 server_name www.subdomain.domain.com;
 passenger_enabled on;
 passenger_app_env production;
 root /home/sachin/testapp/public;
}
server {
 listen 80;
 server_name subdomain.domain.com;
 return 301 $scheme://www.subdomain.domain.com$request_uri;
Ref. taken from here. 

Install Ruby from source code

You can install ruby with following steps:
sudo apt-get update
sudo apt-get install build-essential libssl-dev libyaml-dev libreadline-dev openssl curl git-core zlib1g-dev bison libxml2-dev libxslt1-dev libcurl4-openssl-dev nodejs libsqlite3-dev sqlite3
Create a temporary folder for the Ruby source files:
mkdir ~/ruby
Move to the new folder:
cd ~/ruby
Download the latest stable Ruby source code. (https://www.ruby-lang.org/en/downloads/)
If 2.1 then
wget http://cache.ruby-lang.org/pub/ruby/2.1/ruby-2.1.1.tar.gz
If 2.2 then
wget http://cache.ruby-lang.org/pub/ruby/2.2/ruby-2.2.0.tar.gz
Decompress the downloaded file:
If 2.1 then
tar -xzf ruby-2.1.1.tar.gz
If 2.2 then
tar -xzf ruby-2.2.0.tar.gz
Select the extracted directory:
cd ruby-2.2.0
Run the configure script. This will take some time as it checks for dependencies and creates a new Makefile, which will contain steps that need to be taken to compile the code:
./configure
Run the make utility which will use the Makefile to build the executable program. This step can take a bit longer:
make
Now, run the same command with the install parameter. It will try to copy the compiled binaries to the /usr/local/bin folder. This step requires root access to write to this directory. It will also take a bit of time:
sudo make install
Ruby should now be installed on the system. We can check it with the following command, which should print the Ruby version:
ruby -v
Finally, we can delete the temporary folder:
rm -rf ~/ruby

Deploy Ruby On Rails Application with Nginx server using Phusion Passenger gem

Here I will show you that how to deploy ruby on rails application with passenger and nginx on digitalocean OR amazon aws server.

Here I have used Ubuntu as operating system.

First of all you can login with root user. For deploy application its better to create new user.

Step 1.) create new user for our application. 
adduser sachin(username)
Step 2.) Give that user to sudo permission so that user will able to do some administrative work
gpasswd -a sachin sudo
Step 3.) Generate ssh key for root user
ssh-keygen
Step 4.) Then read generated key with this and copy it somewhere else or clipboard for further use
cat ~/.ssh/id_rsa.pub
Step 5.) Now you can login into created new user(sachin)
su - sachin
Step 6.) Then we can add root user's key into this user's authorization key and for that we can follow this pattern:
mkdir .ssh
chmod 700 .ssh/
nano .ssh/authorized_keys 
Now insert your public key (which should be in your clipboard or anywhere else you have copied earlier in step 4) by pasting it into the editor. 
chmod 600 .ssh/authorized_keys
exit 
With exit you will logout from user(sachin) and now you are into root user.

Step 7.)  Then again login in sachin user
su - sachin (Make sure you do all later operation with this user)
Step 8.) Set Up Your Domain(Optional)
In order to ensure that your site will be up and visible, you need to set up your DNS records to point your domain name towards your new server. You can find more information on setting up a hostname by following the link. 
Step 9.) Now you need to setup environment for ruby as well rails. We can install ruby from latest source code as well rvm.

Step 10.) Now we need to setup passenger with nginx
        First, install a PGP key:
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 561F9B9CAC40B2F7
Create an APT source file (you will need sudo privileges):
sudo nano /etc/apt/sources.list.d/passenger.list
And insert the following line in the file:
deb https://oss-binaries.phusionpassenger.com/apt/passenger trusty main
Press CTRL+x to exit, type y to save the file, and then press ENTER to confirm the file location.
Change the owner and permissions for this file:
sudo chown root: /etc/apt/sources.list.d/passenger.list
sudo chmod 600 /etc/apt/sources.list.d/passenger.list
Update the APT cache:
sudo apt-get update
Finally, install Passenger with Nginx:
sudo apt-get install nginx-extras passenger
        Note : If you have used rvm then don't do this:
This step will overwrite our Ruby version to an older one. To resolve this, simply remove the incorrect Ruby location and create a new symlink to the correct Ruby binary file:
sudo rm /usr/bin/ruby
sudo ln -s /usr/local/bin/ruby /usr/bin/ruby 
Step 11.) Setup the web server
Open the Nginx configuration file:
sudo nano /etc/nginx/nginx.conf
Find the following lines, in the http block:
# passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;
# passenger_ruby /usr/bin/ruby;
Uncomment both of them. Update the path in the passenger_ruby line. They should look like this:
passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;
passenger_ruby /usr/local/bin/ruby;
Then save file.

You will get path for passenger_root with
passenger-config --root
You will get path for passenger_ruby with
which ruby 
Note: For passenger_ruby
If you have used ruby source code then keep as it is
If you have used rvm without gemset then it should like this:
passenger_ruby /home/sachin/.rvm/gems/ruby-2.2.0/wrappers/ruby
If you have used rvm with gemset named testapp then it should be like this:
passenger_ruby /home/sachin/.rvm/gems/ruby-2.2.0@testapp/wrappers/ruby
Step 12.) Now we need to configure nginx
First, We need to disable the default Nginx configuration. Open the Nginx config file:
sudo nano /etc/nginx/sites-available/default
Find the lines:
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
Comment them out, like this:
# listen 80 default_server;
# listen [::]:80 default_server ipv6only=on;
then Save the file.

        Now, create an Nginx configuration file for our app:
sudo nano /etc/nginx/sites-available/testapp
        Add the following server block. The settings are explained below.(Nginx redirect rules)
        If you have domain name then set it as server_name else add ip address for the server_name. If you are using more then one application with same server with different domain the don't add default_server into listen 80
server {
listen 80 default_server;
server_name subdomain.domain.com;
passenger_enabled on;
passenger_app_env production;
root /home/sachin/testapp/public;
}
         Then create a symlink for it:
sudo ln -s /etc/nginx/sites-available/testapp /etc/nginx/sites-enabled/testapp 

Step 13.) Reload & Restart nginx
Reload: sudo nginx -s reload
Restart: sudo service nginx restart

Friday, August 21, 2015

requirements_debian_update_system ruby-2.2.2 error

Today I got new laptop with Ubuntu 15.04 and I was trying to install ruby on rails with rvm.
I have successfully installed rvm and I can see that rvm is installed properly.
But when I have tried to install ruby within rvm using command 'rvm install 2.2.2' then I got below error.

Error:
sachinlenovo@sachinlenovo-g-5070:~$ rvm install 2.2.2
Searching for binary rubies, this might take some time.
No binary rubies available for: ubuntu/15.04/x86_64/ruby-2.2.2.
Continuing with compilation. Please read 'rvm help mount' to get more information on binary rubies.
Checking requirements for ubuntu.
Installing requirements for ubuntu.
Updating system...................
Error running 'requirements_debian_update_system ruby-2.2.2',
showing last 15 lines of /home/sachinlenovo/.rvm/log/1440068704_ruby-2.2.2/update_system.log
++ case "${TERM:-dumb}" in
++ case "$1" in
++ [[ -t 2 ]]
++ return 1
++ printf %b 'There has been error while updating '\''apt-get'\'', please give it some time and try again later.
404 errors should be fixed for rvm to proceed. Check your sources configured in:
   /etc/apt/sources.list
   /etc/apt/sources.list.d/*.list
\n'
There has been error while updating 'apt-get', please give it some time and try again later.
404 errors should be fixed for rvm to proceed. Check your sources configured in:
   /etc/apt/sources.list
   /etc/apt/sources.list.d/*.list

++ return 100
Requirements installation failed with status: 100.

Then I found solution like this:

RVM will refuse to work, if apt-get update has any errors and it doesn't behave well. If your system's apt sources have an invalid repository than apt-get update gives you 404 or GPG error. This confused me for some time because this invalid or faulty repository has no connection with Ruby as well RVM. and after referring some documentation and solutions I came to know below scenario:

So for check the errors you have to run this command and need to find that which ppa is firing errors:
sudo apt-get update | grep "Failed"
then it will give you result like this:

W: Failed to fetch http://ppa.launchpad.net/chris-lea/node.js/ubuntu vivid main  404  Not Found                                                                                      W: .......                                                         
E: Some index files failed to download. They have been ignored, or old ones used instead.

Then for resolve this error you have to press Windows key and need to search "Software & Updates" 

Then open it and go into Other Software there you can see some URLs which is failed while update.

Then uncheck that urls from this and close this window then you can do 
sudo apt-get update 
and then you can install ruby with
rvm install 2.2.2

Thursday, July 30, 2015

PG::DuplicateColumn: ERROR: column already exists

Error:

PG::DuplicateColumn: ERROR:  column of relation table_name already exists

I am using Ruby On Rails with Postgresql and I faced this issue while I am doing migration.

sachin@sachin:~/demo_app$ rake db:migrate
== 20150710135824 AddStatusToUser: migrating =========================
-- add_column(:users, :status, :integer)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::DuplicateColumn: ERROR:  column "status" of relation "users" already exists
: ALTER TABLE "users" ADD COLUMN "status" integer/home/sachin/.rvm/gems/ruby-2.0.0-p598@demo_app/gems/activerecord-4.1.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:128:in `async_exec'

Solution:

Error indicates that in users table status column is already available. Then I found that earlier I have added same migration and then I have done rake db:migrate that time. So That time this column is created. And now I have added again. That's why I am facing this issue.

So here solution is: We need to remove existing column and then need to do migration. 

For that I have found this ways to resolve this issue:

1.) With ruby on rails,

        Open terminal and run "rails db" command it will connect with database. Then you can drop that added columns from here.

        You need to run this command for alter table:
        ALTER TABLE users DROP COLUMN status;

2.) Open postgresql console for drop column. 
         
         Open terminal and run "psql -U postgres" command then it will open psql console.Then you can drop that added columns from here.

        You need to run this command for alter table:
        ALTER TABLE users DROP COLUMN status;

3.) Add condition in migration

        if column_exists? :table_name, :column_name
                remove_column :table_name, :column_name
        end