LoginSignup
4
3

More than 5 years have passed since last update.

nginx+puma+sinatra サブディレクトリ、unixソケット構成(ポートなんぞ使わん)

Last updated at Posted at 2018-12-20

nginx+puma+sinatra サブディレクトリ、unixソケット構成(ポートなんぞ使わん)

railsアプリケーションでのサブディレクトリ構成は多々記事があったけど、sinatraの記事が少なかったので書きました。
参考になれば幸いです。

今回は下記構成をもとに記事を書きます。

構成

/var/www/
app/
 ├ config/puma.rb
 ├ log/*.log
 ├ tmp/
 │ ├ pids/puma.pid
 │ └ sockets/puma.sock
 ├ config.ru
 └ app.rb

※bundle系ファイル略

url

http://localhost/app
※/appがサブディレクトリ部分

参考のソースはgithubに上がってます。
https://github.com/Gen-Arch/app

インストール

installはgemでもbundleでも、今回はbundleでgemを管理します。

アプリケーションディレクトリ作成

mkdir app
cd app

※ディレクトリ名は何でも(大抵はアプリケーション名)

Gemfile生成

bundle init

生成されたGemfileに下記追記

Gemfile
gem "sinatra"
gem "puma"

gem install

bundle install --path vendor/bundle

sinatra 設定

app.rb
require "sinatra"

#Webサーバーを指定
set :server, :puma

#サブディレクトリを指定
before do
  request.script_name = "/app"
end

#root処理
get "/" do
  "hello world"
end

#redirect処理
#サブディレクトリ運用確認テスト用
get "/redirect" do
  redirect to("dest") 
end

#redirect先
get "/dest" do
  "yattaze"
end

puma設定

config.ru
#sinatraファイル名を指定
require_relative "app"

run Sinatra::Application
config/puma.rb
require "fileutils"

#root path
app_path = File.expand_path("..", __dir__)
tmp_dirs = ["tmp/pids","tmp/sockets" ,"log"]

tmp_dirs.each do |path|
  mk_path = File.join(app_path, path)
  FileUtils.mkdir_p(mk_path) unless Dir.exist?(mk_path)
end

#default directory
directory app_path
#env mode
environment 'production'

#service daemon
daemonize

#process id file
pidfile "#{app_path}/tmp/pids/puma.pid"

#puma status file
state_path "#{app_path}/tmp/pids/puma.state"

#stdout, stderr put file
stdout_redirect "#{app_path}/log/app.log", "#{app_path}/log/app_err.log", true

#thread settting low, high
threads 0, 16

#socket type
#bind 'tcp://0.0.0.0:9292' #=> tcp socket
bind "unix:///#{app_path}/tmp/sockets/puma.sock"

#pumactl
activate_control_app

他設定については下記参照
https://github.com/puma/puma/blob/master/examples/config.rb

nginx設定

下記をnginx.confに追記

location /app/ {
  #rewrite url
  rewrite /app/(.*) /$1  break; 

  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;

  #puma unix socket
  proxy_pass http://unix://var/www/app/tmp/sockets/puma.sock;
}

サービス起動/停止

起動
bundle exec pumactl start
停止
bundle exec pumactl stop

アクセス

nginx rewite確認

http://localhost/app
hello worldが出れば成功

sinatra サブディレクトリ指定確認

http://localhost/app//redirect
yattazeと表示されれば成功

参考文献

リバースプロキシ経由でSinatraアプリケーションを動かす
sinatraをサブディレクトリ(sub uri)で動かす

4
3
1

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