Skip to content

Instantly share code, notes, and snippets.

@m3talsmith
Forked from brobertsaz/serversetup.md
Created December 19, 2012 21:27
Show Gist options
  • Save m3talsmith/4340694 to your computer and use it in GitHub Desktop.
Save m3talsmith/4340694 to your computer and use it in GitHub Desktop.

Ubuntu 12.04, Ruby, Rails, Nginx, Unicorn and git-deploy

In the seemlingly endless search for the actual correct and easy way to deploy a Rails app, we have tried several ways. We tried out using Apache2 and running a cluster of Thin servers. With the built in threading of Puma we decided to use it with Nginx.

Server Setup

  • Create new server
  • Login to new server
    • ssh root@IPaddress (you can also use the domain name if you have the DNS setup already)
    • accept the RSA key
    • use the password that was provided when you set up the new server:
      • change the password:
passwd
  • Create new user for deployment
sudo adduser <username>
  • accept the defaults
  • add new user to staff and sudo groups:
sudo adduser <username> staff
sudo user <username> sudo
  • switch user
su <username>
  • Update and Install dependencies:
sudo apt-get -y update
 
sudo apt-get -y install build-essential zlib1g-dev libssl-dev libreadline-dev libyaml-dev libcurl4-openssl-dev curl git-core python-software-properties libxslt1-dev libxml2-dev libmysqlclient-dev libsqlite3-dev nodejs
  • To make life easier, lets go ahead and add our ssh keys to the new server so that we do not have to sign in every time. (THis is done from your local terminal and not on the new server):

Add ssh keys

mkdir ~/.ssh
cat ~/.ssh/id_rsa.pub | ssh root@IPaddress "cat >> ~/.ssh/authorized_keys"

Install Ruby

Install your Ruby (obviously you use the version that you want. At this point many people use a Ruby version management like RVM or RBENV. As these servers are normally setup for just on application we will use the system version of Ruby):

su root

wget ftp://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-p194.tar.gz
 
tar -xvzf ruby-1.9.3-p194.tar.gz
 
cd ruby-1.9.3-p194/
 
./configure
 
make
 
sudo make install
 
echo "gem: --no-ri --no-rdoc" >> ~/.gemrc
 
sudo gem install bundler

Database Setup

Setup mySQL:

sudo apt-get install mysql-server mysql-client libmysqlclient-dev
 
   * If you need to add your user to the mysql database:
 
mysql -u root
 
mysql > CREATE USER <username>;
 
mysql > GRANT ALL ON *.* TO <username>;
 
mysql > FLUSH PRIVILEGES;

Rails Deployment

For Rails deployment we like to use git-deploy created by Mislav Marohnić. The setup directions are quite simple but we have noticed a slight issue in that the Rails application it self is constantly updating files with in itself.

To remedy this, we create two directories and a few sub-directories for our Rails application:

mkdir /webapps/myapp/repository
mkdir /webapps/myapp/shared
mkdir /webapps/myapp/shared/log
mkdir /webapps/myapp/shared/pids
mkdir /webapps/myapp/shared/system

Then in the setup for git-deploy, we use the repository for the remote:

git remote add production <username>@IPaddres:/webapps/myapp/repository

From there, follow the setup directions for git-deploy.

Nginx

Install Nginx:

sudo apt-get install nginx

Nginx will create several files for you. Setting these files up properly seems to be the biggest issue in the entire server setup. If you spand enough time you will find a multitude of different ways to configure these files. The following files are how I configured them and they work for me.

The nginx.conf file that is created required no editing for my setup to work:

user www-data;
worker_processes 4;
pid /var/run/nginx.pid;

events {
        worker_connections 768;
}

http {
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        gzip on;
        gzip_disable "msie6";

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

Nginx works with several sites on a server. These sites are listed in the sites available directory for Nginx (etc/nginx/sites-available/) and includes a default on install.

Add a new file in the site-available directory and copy and paste the following into it:

upstream myapplication {
    server unix:/tmp/myapplication.sock fail_timeout=0;
}

server {
  listen                80; # default;
  server_name           staging.pathwaystv.com;
  root                  /path/to/myapplication/public;

  location / {
    access_log          off;

    include proxy_params;
    proxy_redirect off;

    if (-f $request_filename) {
      access_log          off;
      expires             max;
      break;
    }

    if (-f $request_filename.html) {
      rewrite (.*) $1.html break;
    }

    if (!-f $request_filename) {
      proxy_pass          http://myapplication;
      break;
    }
  }
}

After creating this new file, we need to symlink it to the sites-available directory:

sudo ln -s /etc/nginx/sites-available/<filename> <filename>

Unicorn

Unicorn was installed by including the gem in our Gemfile.

From the root of the project:

curl -o config/unicorn.rb https://raw.github.com/defunkt/unicorn/master/examples/unicorn.conf.rb

This will create a new unicorn.conf file:

worker_processes 4
working_directory "/path/to/myapplication"

listen "/tmp/pathwaystv.sock", :backlog => 64
listen 8080, :tcp_nopush => true

timeout 30

pid "/path/to/myapplication/pids/unicorn.pid"

stderr_path "/path/to/myapplication/log/unicorn.stderr.log"
stdout_path "/path/to/myapplication/log/unicorn.stdout.log"

preload_app true
GC.respond_to?(:copy_on_write_friendly=) and
  GC.copy_on_write_friendly = true

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

   old_pid = "#{server.config[:pid]}.oldbin"
   if old_pid != server.pid
     begin
       sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
       Process.kill(sig, File.read(old_pid).to_i)
     rescue Errno::ENOENT, Errno::ESRCH
     end
   end
end

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

Create a Unicorn initializer shell script in the /etc/init.d/ directory:

touch /etc/init.d/unicorn

vim /etc/init.d/unicorn

Paste the following into that new file:

#! /bin/bash

USER="username"
DAEMON=unicorn
DAEMON_OPTS="-c /path/to/myapplication/config/unicorn.rb -E staging -D"
NAME=unicorn
DESC="Unicorn app for $USER"
PID=/path/to/myapplication/shared/pids/unicorn.pid

case "$1" in
  start)
        CD_TO_APP_DIR="cd /path/to/myapplication"
        START_DAEMON_PROCESS="bundle exec $DAEMON $DAEMON_OPTS"

        echo -n "Starting $DESC: "
        if [ `whoami` = root ]; then
          su - $USER -c "$CD_TO_APP_DIR > /dev/null 2>&1 && $START_DAEMON_PROCESS"
        else
          $CD_TO_APP_DIR > /dev/null 2>&1 && $START_DAEMON_PROCESS
        fi
        echo "$NAME."
        ;;
  stop)
        echo -n "Stopping $DESC: "
        kill -QUIT `cat $PID`
        echo "$NAME."
        ;;
  restart)
        echo -n "Restarting $DESC: "
        kill -USR2 `cat $PID`
        echo "$NAME."
        ;;
  reload)
        echo -n "Reloading $DESC configuration: "
        kill -HUP `cat $PID`
        echo "$NAME."
        ;;
  *)
        echo "Usage: $NAME {start|stop|restart|reload}" >&2
        exit 1
        ;;
esac

exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment