LoginSignup
19
18

More than 5 years have passed since last update.

Sinatra + Thin + NginxでWEBアプリケーション運用

Last updated at Posted at 2016-01-02

概要

Sinatraで作ったWEBアプリケーションをThin + Nginxで運用する。
本当はUnicornの方が早いらしいが、SinatraのチュートリアルでThinが紹介されており、手軽さを重視しThinで構築した。
また、Thin単体で動かすとなぜかSSL通信時にセッションが維持されないという現象に直面したので、Nginxをフロント、Thinをバックエンドサーバーとして動かすことにした。

環境

  • Ubuntu 14.04.2 LTS
  • Ruby 2.0.0-p645
  • Nginx 1.4.6
  • Sinatra 1.4.6
  • Thin 1.6.4

設定

最小のファイル構造。

.
|-- Gemfile
|-- app.rb
|-- config.ru

Sinatraの設定

config.ruを記述し、Sinatraをモジュールとして起動できるようにする。

config.ru
require './app'
run Application
app.rb
require 'bundler/setup'
require 'sinatra/base'

class Application < Sinatra::Base
  get '/' do
    'hello,world!'
  end
end

Thinの設定

GemfileにThinを書いておく。

Gemfile
gem 'sinatra' , '1.4.6'
group :production do
  gem 'thin'
end

bundle installの後に、Thinをサービスとして起動する設定を行う。
rootで実行する必要があるため、環境変数PATHを引き継ぐ設定にするか、bundleを直接叩く。

$ which bundle
/home/kazuya/.rbenv/shims/bundle
$ sudo /home/kazuya/.rbenv/shims/bundle exec thin install
Installing thin service at /etc/init.d/thin ...
mkdir -p /etc/init.d
writing /etc/init.d/thin
chmod +x /etc/init.d/thin
mkdir -p /etc/thin

To configure thin to start at system boot:
on RedHat like systems:
  sudo /sbin/chkconfig --level 345 thin on
on Debian-like systems (Ubuntu):
  sudo /usr/sbin/update-rc.d -f thin defaults
on Gentoo:
  sudo rc-update add thin default
$ sudo /usr/sbin/update-rc.d -f thin defaults

これでThinがサービスとして自動起動するようになる。

次にThinの設定ファイルを作成する。

/etc/thin/hoge.yml
---
chdir: /path/to/your/application
environment: production
timeout: 30
log: log/thin.log
pid: tmp/pids/thin.pid
max_conns: 1024
max_persistent_conns: 100 
require: []
wait: 30
threadpool_size: 20
socket: /tmp/hoge.1.sock
daemonize: true

これでThin起動時に上記の設定が読み込まれる。

Nginxの設定

Thinとは/tmp/hoge.1.sockを通じてやりとりする。
SSL周りの詳細な設定は、また別の機会に。

/etc/nginx/sites-available/hoge-service.com
upstream backend {
    server unix:/tmp/hoge.1.sock;
    ip_hash;
}

server {
    listen       80;
    listen       443;
    server_name hoge-service.com;

    ssl on;
    ssl_certificate /etc/nginx/ssl-files/server.crt;
    ssl_certificate_key /etc/nginx/ssl-files/server.key;

    location / {
        proxy_pass http://backend;
    }
}

以上で完了。
ちゃんとしたサービスとして運用するには、負荷を考えThinのクラスタリング等のチューニングすべきかもしれない。

19
18
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
19
18