LoginSignup
3
7

More than 5 years have passed since last update.

unicorn で Hello World!

Last updated at Posted at 2016-05-26

nginx + unicorn + rails という構成がごく普通だが、nginx と unicorn の接続にハマったため、問題を切り分けるためにそもそも、unicorn とはなんぞやというところからはじめることにした。

unicorn は Rack アプリを動かせるウェブサーバである。
実用性はゼロだが、unicorn だけで一度動かしてみた。

AWSで、unicorn + nginx + sinatra を動かしてみる
http://qiita.com/konpyu/items/3ba3774bcde226d7d07d
を参考にさせていただいた。

準備

$ mkdir helloworld
$ cd helloworld
$ vi Gemfile
$ vi config.ru

Gemfile:

source "https://rubygems.org"

gem "unicorn"
gem "sinatra"

config.ru:

require 'rubygems'
require 'sinatra/base'
class HelloApp < Sinatra::Base
  get '/' do
    'Hello World!'
  end
end
run HelloApp

ここまで準備したら、

$ bundle install
$ bundle exec unicorn

すると、

I, [2016-05-26T16:11:56.939643 #17527]  INFO -- : listening on addr=0.0.0.0:8080 fd=9
I, [2016-05-26T16:11:56.939867 #17527]  INFO -- : worker=0 spawning...
I, [2016-05-26T16:11:56.940895 #17527]  INFO -- : master process ready
I, [2016-05-26T16:11:56.941741 #17529]  INFO -- : worker=0 spawned pid=17529
I, [2016-05-26T16:11:56.942187 #17529]  INFO -- : Refreshing Gem list
I, [2016-05-26T16:11:57.006805 #17529]  INFO -- : worker=0 ready

と unicorn が起動。

http://localhost:8080/

Hello World!

と表示される。

後日談

私がはまっていた問題というのは、nginx でアクセスすると、502 Bad Gateway と表示されるものだったのだが、実は、単に unicorn が起動していなかったぽい…。やれやれ。仕組みを知らずに使っていると問題の核心に近づくのに時間がかかる、という教訓だった。

nginx と unicorn は通常、Unix ドメインソケットでつなぐが、この設定は、unicorn側では、設定ファイルに、

listen "someappdir/app.sock"

などと書いておけば良いようだ。

ちなみに nginx 側は、

upstream app-production {
  server unix:/someappdir/app.sock fail_timeout=0;
}

みたいにしておく。

3
7
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
3
7