LoginSignup
14
11

More than 5 years have passed since last update.

Unicorn + Nginxを理解する

Posted at

と言っても深すぎるところまではやれないと思うけど、理解しながら利用する方がいいはずなので、できる限りを努める。

temに置くpidとsocketはなんぞや

pid (プロセス識別子)

参考:wikipedia

pidファイル
長時間動作し続けるプロセス(例えば MySQL デーモンなど)は、自身のPIDをファイルに書いておき、他のプロセスが参照できるようにしていることがある。

socket(ソケット)

ソケット通信では,前もって「待ち合わせた」ところでお互いにソケット同士をつなぎ合わせて通信路を作ります。待ち合わせる場所はソケットの種別によって変わってきますが,最もよく用いられるTCP/IPのソケットでは,ホスト(ホスト名またはIPアドレスで指定)とポート(1から65535までの整数で指定)の組み合わせで待ち合わせます。

参考:itpro
https://ja.wikipedia.org/wiki/UNIXドメインソケット

…🤔

これだけだとイマイチ正確に理解した気にはなれないが、プロセス間やネットワーク間でやりとりをする時に、受け渡しのようなことをするためのものっていう理解で現時点はなった。(ちゃんと勉強しよ)

で、結局UnicornとNginxでどうやって設定するの?

rails_root/config/unicorn.rb
#Unicornのログ出力先を指定
#File.expand_pathはパスを絶対パスに解決するメソッド File.expand_path: https://ruby-doc.org/core-2.2.0/File.html#method-c-expand_path
rails_root = File.expand_path('../../', __FILE__)
#ワーカー数を指定する
worker_processes 2
working_directory rails_root

listen "#{rails_root}/tmp/sockets/unicorn.sock" #??「Unicornのプロセスをlistenするアドレストポートを指定」らしいが…;socketsを追加。
pid "#{rails_root}/tmp/pids/unicorn.pid" #pid fileの位置を指定する。pidsを追加。

#ログの出力先を指定
stderr_path "#{rails_root}/log/unicorn_error.log"
stdout_path "#{rails_root}/log/unicorn.log"

再起動(のうちの停止)を変更したパスに従って変更する。

/usr/local/etc/nginx/nginx.conf
upstream unicorn {
        # nginxとunicornの連携
        # unicorn.rbで設定したunicorn.sockを指定
        server unix:{RAILS_PROJECT_ROOT}/tmp/sockets/unicorn.sock; #ソケットはこいつだ!socketsを追加
    }

server {
        listen 8081;
        server_name {PROJECTDOMAIN_FOR_LOCAL};

        root {RAILS_PROJECT_ROOT}/public;

        access_log /usr/local/var/log/nginx/{PROJECT_NAME}_access.log;
        error_log /usr/local/var/log/nginx/{PROJECT_NAME}_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;
        }
    } 
14
11
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
14
11