HEYBlog about Technology

京都の学生エンジニアのエンジニアブログ

SinatraとかUnicornとか

Sinatraの業務が出来たので、ちょっとメモしておく。

ってか、初Rubyやったね!

UnicornとかPassengerは聞いたことある!

Sinatra

nginxとunicorn

参考文献

[nginx]

upstream app1 {
             server unix:/tmp/app1.sock;
    }

    server {
           listen 3001;
           server_name localhost;

           location / {
                    root /SinatraProduct/public;
                    proxy_pass http://app1;
                    proxy_set_header Host $host;

           }
    }

[unicorn.rb]

# -*- coding: utf-8 -*-                                                                
# unicorn.rb                                                                           
# coding: utf-8                                                                        

# プロジェクトディレクトリへのパス                                                     
@path = "/SinatraProduct/"

worker_processes 1 # CPUのコア数に揃える                                               
working_directory @path
timeout 300
listen '/tmp/app1.sock' # Nginxのconfig内にあるupstreamで、このパスを指定              
pid "#{@path}tmp/pids/unicorn.pid" # pidを保存するファイル                             
# logを保存するファイル                                                                
stderr_path "#{@path}log/unicorn.stderr.log"
stdout_path "#{@path}log/unicorn.stdout.log"
preload_app true

nginx

sudo nginx #起動
sudo nginx -s stop #停止

Unicorn

bundle exec unicorn -c unicorn.rb -D
#-Dでデーモン化

これでlocalhost:3001で見れるはず

Erbテンプレートを使う

[Gemfile]

gem install bundler
cd project
bundle init

#Gemfileが生成される

入れたいgemをGemfileに書く

source "https://rubygems.org"
gem 'sinatra'
gem 'haml'
gem 'mysql2'
gem 'activerecord'
gem 'unicorn'

gem関連インストール

bundle install --path vendor/bundle

erbテンプレートの追加

[Gemfile]

gem 'erb'

[views/index.html.erb]
require 'erb'

get '/' do
    erb :index.html
end

エラー関連

unicorn + nginxで502

unicornの起動側でエラーはいているっぽいから logを見てあげれば良い

emacs DocumentRoot/log/unicorn.stderr.log 
DocumentRoot/vendor/bundle/ruby/2.0.0/gems/unicorn-4.7.0/lib/unicorn/configurator.rb:91:in `block in reload': directory for pid=DocumentRoot/tmp/pids/unicorn.pid not writable (ArgumentError)

[答え] ちゃんとディレクトリ掘れてるかチェックしろカス