17
12

More than 1 year has passed since last update.

nginx + unicorn を使用してみた (Mac & Heroku)

Last updated at Posted at 2020-10-03

nginx + Unicorn + rails の導入方法(ローカル環境)

unicorn

Gemfileにunicornのgemを追加

Gemfile.rb
#Gemfileに追加
gem 'unicorn'
gem 'unicorn-rails'

bundle installを実行する

bundle install

unicornの設定ファイルを作成

unicorn.rb
# config/unicorn.rb に下記内容を記載
# ※パスは変更する。
rails_root = File.expand_path('../../', __FILE__)

worker_processes 2
working_directory rails_root

listen "#{rails_root}/tmp/unicorn.sock"
pid "#{rails_root}/tmp/unicorn.pid"

stderr_path "#{rails_root}/log/unicorn_error.log"
stdout_path "#{rails_root}/log/unicorn.log"

デーモンとして起動

# 対象のrailsアプリケーションのディレクトリ内にいること
unicorn_rails -c config/unicorn.rb -E development -D

停止

# 対象のrailsアプリケーションのディレクトリ内にいること
kill -QUIT `cat tmp/unicorn.pid`

nginx

brewコマンドでインストール

brew install nginx

起動確認

sudo nginx

設定ファイル編集

バックアップをしてからnginx.conf.defaultをコピーする。

cd /usr/local/etc/nginx
cp nginx.conf nginx.conf.YYYYMMDD
cp nginx.conf.default nginx.conf

nginx.confの編集を行う
※パスは変更する


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       8080;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
    include servers/*;
    upstream unicorn {
        # nginxとunicornの連携
        # unicorn.rbで設定したunicorn.sockを指定
        server unix:/Users/yotanaka/diveintocode/nginx_rails_app/tmp/unicorn.sock;
    }

server {
        listen 8081;
        server_name localhost;

        root /Users/yotanaka/diveintocode/nginx_rails_app/public;

        access_log /usr/local/var/log/nginx/nginx_app_access.log;
        error_log /usr/local/var/log/nginx/nginx_app_access_error.log;

        client_max_body_size 100m;
        error_page 500 502 503 504 /500.html;

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

        location @unicorn {
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_pass http://unicorn;
        }
    }   
}

nginx再起動

sudo nginx -s reload

起動確認

下記アドレスにアクセスしRailsの画面が表示されることを確認する。

nginx + Unicorn + rails の導入方法(HEROKU環境)

Herokuのアプリケーションを作成する

対象のアプリケーションフォルダ内で下記コマンドを実行する。

rails assets:precompile RAILS_ENV=production
git add .
git commit -m 'コミットメッセージ'
git push heroku master
heroku run rails db:migrate

buildpacksを導入

下記コマンドを対象のRailsアプリケーションフォルダ内で実行

heroku buildpacks:add heroku-community/nginx

設定ファイル修正

アプリケーションフォルダの直下にProcfileを作成する

作成後下記内容を記述

※ vim Procfile

web: bin/start-nginx bundle exec unicorn -c config/unicorn.rb

unicorn.rbを修正する。

※ vim config/unicorn.rb

unicorn.rb
require 'fileutils'
listen '/tmp/nginx.socket'
before_fork do |server,worker|
	FileUtils.touch('/tmp/app-initialized')
end

修正内容をコミットする

git add .
git commit -m 'コミットメッセージ '

Herokuにデプロイする

git push heroku master

参考

Nginx+UnicornでRailsを動かすon Mac
heroku-buildpack-nginx
Rails と Rack
なぜrailsの本番環境ではUnicorn,Nginxを使うのか?  ~ Rack,Unicorn,Nginxの連携について ~【Ruby On Railsでwebサービス運営】
Rails開発におけるwebサーバーとアプリケーションサーバーの違い(翻訳)
なぜRailsのWebアプリにunicornが必要なのか
Herokuに必要なProcfileの書き方についてまとめておく
unicornの起動と終了

17
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
12