SinatraとUnicorn、ちょっとした設定など
毎回ググっててあほらしいので記事として残しておく。
環境
$ ruby -v ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-linux]
Gemfileを書くよ
早速bundle init
してGemfileを書こう。
$ bundle init
Writing new Gemfile to /path/to/dir
$ ls
Gemfile
$ vim Gemfile
gem 'sinatra' gem 'sinatra-contrib' # 検証してるときに便利だった gem 'unicorn'
書けたら颯爽とbundle install
するぞ。
$ bundle install --path vender/bundle
ファイルとディレクトリを作っていく
とりあえず以下のようになった。
project_root - main.rb - config.ru - Gemfile - views - index.erb - public - css - skelton.css - normalize.css - vender
この記事で出番はないけど、Skeletonはいいぞ。
ファイルを編集していく
がんがんファイルを編集していく。
# main.rb require 'sinatra/base' require 'sinatra/reloader' require 'unicorn' class TestSinatra < Sinatra::Base get '/' do @content = 'Hello, world' erb :index end end
# config.ru require './main.rb' run TestSinatra
# views/index.erb <html> <head> <link rel="stylesheet" type="text/css" href="normalize.css"> <link rel="stylesheet" type="text/css" href="skeleton.css"> </head> <body> <%= @content %> </body> </html>
起動してみよう
いざ起動。
$ bundle exec unicorn I, [2017-02-10T21:37:52.717122 #8014] INFO -- : listening on addr=0.0.0.0:8080 fd=13 I, [2017-02-10T21:37:52.717208 #8014] INFO -- : worker=0 spawning... I, [2017-02-10T21:37:52.717779 #8014] INFO -- : master process ready I, [2017-02-10T21:37:52.718149 #8043] INFO -- : worker=0 spawned pid=8043 I, [2017-02-10T21:37:52.718266 #8043] INFO -- : Refreshing Gem list I, [2017-02-10T21:37:52.748041 #8043] INFO -- : worker=0 ready
ブラウザでlocalhost:8080
にアクセスできるぞい。
Unicornの設定をしてみる
Unicornの設定も当然できるらしいのでやってみよう。
@path = File.expand_path(File.dirname(__FILE__)) worker_processes 1 working_directory @path timeout 100 listen '/tmp/testsinatra.sock' pid "#{@path}/unicorn.pid" stderr_path "#{@path}/uni_err.log" stdout_path "#{@path}/uni_out.log"
実行して、アクセスしてみる。
$ bundle exec unicorn -c unicorn.rb -D $ curl --unix-socket /tmp/testsinatra.sock http://localhost/ <html> <head> <link rel="stylesheet" type="text/css" href="normalize.css"> <link rel="stylesheet" type="text/css" href="skeleton.css"> </head> <body> Hello, world </body> </html>
-D
オプションでデーモン化しているので、殺したいときは以下のように。
$ kill $(cat unicorn.pid)