Qiang Blog

Just another zhangjingqiang's blog.

How To Deploy Rails Apps Using Unicorn And Nginx on CentOS 7.3

Set iptables

yum install iptables-services
iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
service iptables save

Install git and nginx

yum install -y epel-release git nginx

Change nginx default setting file

/etc/nginx/nginx.conf

user root;
...

#    server {
#        listen       80 default_server;
#        listen       [::]:80 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#   }

Create rails.conf under /etc/nginx/conf.d/

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

server {
    listen 80;
    server_name node1;

    # Application root, as defined previously
    root /home/deploy/myapp/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_set_header X-FORWARDED_PROTO https;
        proxy_pass http://app;
    }

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

Check syntax and restart Nginx

nginx -t
systemctl restart nginx

Install rbenv

git clone https://github.com/rbenv/rbenv.git ~/.rbenv
git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
~/.rbenv/bin/rbenv init

Switch ruby

rbenv install 2.3.1
rbenv global 2.3.1
rbenv rehash

Install bundler, rails and unicorn

gem install bundler
gem install rails -v 5.0.0
gem install unicorn

Change to myapp path

cd /home/deploy/myapp

Setup

bundle install
RAILS_ENV=production bundle exec rails assets:precompile
RAILS_ENV=production bundle exec rails db:migrate

Start unicorn

bundle exec unicorn_rails -c config/unicorn.rb -D -E production

centos nginx rails unicorn