「Ruby on Rails」の版間の差分

提供: ArchWiki
ナビゲーションに移動 検索に移動
(ページの作成:「Category:ウェブサーバー en:Ruby on Rails zh-CN:Ruby on Rails {{Related articles start}} {{Related|Ruby}} {{Related|Nginx}} {{Related|LAMP}} {{Related|M...」)
 
 
(3人の利用者による、間の24版が非表示)
1行目: 1行目:
[[Category:ウェブー]]
+
[[Category:ウェブフレムワ]]
 
[[en:Ruby on Rails]]
 
[[en:Ruby on Rails]]
[[zh-CN:Ruby on Rails]]
+
[[zh-hans:Ruby on Rails]]
 
{{Related articles start}}
 
{{Related articles start}}
 
{{Related|Ruby}}
 
{{Related|Ruby}}
8行目: 8行目:
 
{{Related|MySQL}}
 
{{Related|MySQL}}
 
{{Related articles end}}
 
{{Related articles end}}
[http://rubyonrails.org/ Ruby on Rails] (よく Rails とか RoR と略されます) は Ruby プログラミング言語によるオープンソースのウェブアプリケーションフレームワークです。Rails はウェブ開発者によって高速な開発のために使用されているアジャイル開発で使われるように出来ています。
+
[http://rubyonrails.org/ Ruby on Rails] (よく Rails とか RoR と略されます) は [[Ruby]] プログラミング言語によるオープンソースのウェブアプリケーションフレームワークです。Rails はウェブ開発者によって高速な開発のために使用されているアジャイル開発で使われるように出来ています。
   
 
このドキュメントでは Arch Linux システムで Ruby on Rails フレームワークをセットアップする方法を説明します。
 
このドキュメントでは Arch Linux システムで Ruby on Rails フレームワークをセットアップする方法を説明します。
14行目: 14行目:
 
== インストール ==
 
== インストール ==
   
  +
Ruby on Rails は まず Ruby のインストールが必要なので、インストール方法はまずその記事を読んでください。nodejs パッケージは ([https://github.com/mishoo/UglifyJS2 UglifyJS JavaScript compressor] の Ruby ラッパー、オプション) を使う場合にも必要です。Rails フレームワークは Ruby のバージョン (またはシステムの Ruby インストール) にリンクされています。インストールされる Ruby のバージョンは、システム、rbenv、rvm (Ruby Version Manager) のいずれでもかまいません。
Ruby on Rails requires [[Ruby]] to be installed, so read that article first for installation instructions. The {{pkg|nodejs}} package is also required.
 
   
  +
=== RubyGems ===
Ruby on Rails itself can be installed multiple ways:
 
   
  +
{{Note|Gem を使ってシステム全体に Rails をインストールすることもできます。その場合、以下のコマンドを root で実行して {{ic|--no-user-install}} を付けて下さい。root で RubyGem を使用する危険性については [[Ruby#gem をユーザー個別またはシステム共通でインストール]] を読んで下さい。}}
=== 選択肢 A: RubyGems ===
 
   
  +
現在のユーザーで Rails をインストールするコマンド:
{{Note|You can also install Rails system-wide using Gems. To do this, run the following commands as root and append them with {{ic|--no-user-install}}. Please read [[Ruby#Installing gems per-user or system-wide]] for possible dangers of using RubyGem in this way.}}
 
 
The following command will install Rails for the current user:
 
 
$ gem install rails
 
$ gem install rails
   
  +
ドキュメントのビルドには時間がかかります。ドキュメントは不要の場合、{{ic|--no-document}} を install コマンドに付けて下さい。
Building the documentation takes a while. If you want to skip it, append {{ic|--no-document}} to the install command.
 
 
$ gem install rails --no-document
 
$ gem install rails --no-document
   
  +
gem は Ruby モジュールのパッケージマネージャであり、Arch Linux における pacman のようなものです。gem をアップデートするには、次を実行:
gem is a package manager for Ruby modules, somewhat like pacman is to Arch Linux. To update your gems, simply run:
 
 
$ gem update
 
$ gem update
   
=== 選択肢 B: pacgem ===
+
=== Pacman ===
 
You can install Rails using {{AUR|pacgem}} from the [[AUR]]. Pacgem automatically creates PKGBUILDs and Arch packages for each of the gems. These packages will then be installed using pacman.
 
# pacgem rails
 
 
The gem packages can be updated with
 
# pacgem -u
 
 
=== 選択肢 C: AUR ===
 
 
{{Warning|This is not recommended, as this might not include the latest Rails version, and additional dependencies may be introduced that may require you to run {{Ic|gem install}} anyway.}}
 
   
  +
{{AUR|ruby-rails}} パッケージを [[インストール]] します。もしくは、[[Ruby#pacman を使って RubyGems を管理する]] を見て下さい。
There is a {{AUR|ruby-rails}} package available in the [[AUR]].
 
   
=== 選択肢 D: Quarry バイナリリポジトリ ===
+
=== Quarry バイナリリポジトリ ===
   
  +
非公式の [[非公式ユーザーリポジトリ#quarry|quarry]] リポジトリから ''ruby-rails'' を[[インストール]]してください。
[[pacman|Install]] ''ruby-rails'' from the unofficial [[Unofficial user repositories#quarry|quarry]] repository.
 
   
 
== 設定 ==
 
== 設定 ==
   
  +
Rails には WeBrick という名前のベーシックな HTTP サーバーが付属しています。テストアプリケーションを作成してテストすることができます。まず、rails コマンドでアプリケーションを作成:
Rails is bundled with a basic HTTP server called WeBrick. You can create a test application to test it. First, create an application with the rails command:
 
   
 
$ rails new testapp_name
 
$ rails new testapp_name
   
{{Note|If you get an error like {{ic|Errno::ENOENT: No such file or directory (...) An error occurred while installing x, and Bundler cannot continue.}}, you might have to configure [[Ruby#Bundler|Bundler]] so that it installs gems per-user and not system-wide. Alternatively, run {{ic|# rails new testapp_name}} once as root. If it has completed successfully, delete {{ic|testapp_name/}} and run {{ic|$ rails new testapp_name}} again as a regular user.}}
+
{{Note|{{ic|Errno::ENOENT: No such file or directory (...) An error occurred while installing x, and Bundler cannot continue.}} などのエラーが表示されたら、[[Ruby#Bundler|Bundler]] を設定して gem をシステム全体ではなくユーザー個別でインストールする必要があります。もしくは、root {{ic|# rails new testapp_name}} を一度実行してください。問題なくインストールが完了したら、{{ic|testapp_name/}} を削除して、{{ic|$ rails new testapp_name}} をもう一度、通常ユーザーで実行してください。}}
{{Note|If you get an error message like this:
 
{{ic|... FetchError: SSL_connect returned=1 errno= 0 state=SSLv2/v3 read server hello A: sslv3 alert handshake
 
failure <nowiki>(https://s3.amazonaws.com/ production.s3.rubygems.org/gems/rake-10.0.3.gem)</nowiki> }}
 
install {{Pkg|nodejs}} and try again.}}
 
   
  +
これにより、現在の作業ディレクトリの中に新しいフォルダが作成されます。
This creates a new folder inside your current working directory.
 
   
 
$ cd testapp_name
 
$ cd testapp_name
   
  +
次に Web サーバを起動します。デフォルトではポート3000で待ち受けます。
Next start the web server. It listens on port 3000 by default:
 
   
 
$ rails server
 
$ rails server
   
Now visit the testapp_name website on your local machine by opening <nowiki>http://localhost:3000</nowiki> in your browser
+
ブラウザで <nowiki>http://localhost:3000</nowiki> を開いて、ローカルマシンの testapp_name ウェブサイトにアクセスします。
{{Note|If Ruby complains about not being able to find a JavaScript runtime, install {{Pkg|nodejs}}.}}
+
{{Note|Ruby JavaScript ランタイムを見つけられないと、表示される場合は、{{Pkg|nodejs}}をインストールして下さい。}}
   
  +
テストページが表示され、"Welcome aboard "と挨拶されるはずです。
A test-page should shown greeting you "Welcome aboard".
 
   
 
== アプリケーションサーバー ==
 
== アプリケーションサーバー ==
   
The built-in Ruby On Rails HTTP server (WeBrick) is convenient for basic development, but it is not recommended for production use. Instead, you should use an application server such as [[#Thin]], [[#Unicorn]] or [[#Apache/Nginx (using Phusion Passenger)|Phusion Passenger]].
+
Ruby On Rails に内蔵されている HTTP サーバー (WeBrick) は開発用には便利ですが、本番環境での使用は推奨されません。[[#Thin]], [[#Unicorn]], [[#Apache/Nginx (Phusion Passenger を使用)|Phusion Passenger]] などのアプリケーションサーバーを使って下さい。
   
 
=== Thin ===
 
=== Thin ===
   
[http://code.macournoyer.com/thin/ Thin]
+
[http://code.macournoyer.com/thin/ Thin] は高速でシンプルな Ruby ウェブサーバーです。
   
  +
thin の gem をまずインストールしてください:
First install thin gem:
 
 
$ gem install thin
 
$ gem install thin
   
  +
そして次のコマンドで起動:
Then start it using:
 
 
$ thin start
 
$ thin start
   
 
=== Unicorn ===
 
=== Unicorn ===
   
  +
Unicorn はスタンドアロンのアプリケーションサーバーで、クライアントと直接対話することはできません。その代わりに、ウェブサーバーがクライアントと Unicorn の間に入って、必要に応じてリクエストを送ります。[http://unicorn.bogomips.org/ Unicorn] は基本的に Mongrel が元になっています。Unicorn は Github に使われており、リクエストを処理するのに一番適した子プロセスを出来る限り使うようなアーキテクチャになっています。Unicorn と Mongrel の違いについては [https://github.com/blog/517-unicorn こちら] に説明があります。
Unicorn is a stand-alone application server that cannot talk directly to clients. Instead, a web server must sit between clients and Unicorn, proxying requests as needed. [http://unicorn.bogomips.org/ Unicorn] is loosely based on Mongrel. It is used by Github, and it uses an architecture that tries hard to find the best child for handling a request. [https://github.com/blog/517-unicorn Explanation of differences between Unicorn and Mongrel].
 
   
Install the Unicorn gem:
+
Unicorn gem をインストール:
 
# gem install unicorn
 
# gem install unicorn
   
Then create a configuration file for your application in {{ic|/etc/unicorn/}}. For example; here is a configuration example (Based on [http://www.warden.pl/2011/01/07/running-redmine-under-unicorn-in-debian/]) for Redmine:
+
アプリケーションの設定ファイルを {{ic|/etc/unicorn/}} に作成。以下は Redmine の設定例です ([http://www.warden.pl/2011/01/07/running-redmine-under-unicorn-in-debian/] を参照):
   
 
{{hc|/etc/unicorn/redmine.ru|<nowiki>
 
{{hc|/etc/unicorn/redmine.ru|<nowiki>
120行目: 104行目:
 
</nowiki>}}
 
</nowiki>}}
   
  +
次のコマンドで起動:
Start it using:
 
# usr/bin/unicorn -D -E production -c /etc/unicorn/redmine.ru
+
# /usr/bin/unicorn -D -E production -c /etc/unicorn/redmine.ru
   
 
==== Systemd サービス ====
 
==== Systemd サービス ====
   
Put the following contents in {{ic|/etc/systemd/system/unicorn.service}}:
+
{{ic|/etc/systemd/system/unicorn.service}} に以下を記述:
 
{{hc|/etc/systemd/system/unicorn.service|2=
 
{{hc|/etc/systemd/system/unicorn.service|2=
 
[Unit]
 
[Unit]
140行目: 124行目:
 
}}
 
}}
   
  +
これで systemctl を使って簡単に unicorn を起動・停止できます。
You can now easily start and stop unicorn using systemctl
 
   
 
==== Nginx の設定 ====
 
==== Nginx の設定 ====
   
  +
[[Nginx]] をセットアップしてから、以下のように unicorn を上流サーバーとして設定してください (警告: 以下は省略した例です。おそらく設定を追加しないと機能しません):
After setting up [[Nginx]], configure unicorn as an upstream server using something like this (Warning: this is a stripped example. It probably doesn't work without additional configuration):
 
 
{{bc|1=
 
{{bc|1=
 
http {
 
http {
171行目: 155行目:
 
=== Apache/Nginx (Phusion Passenger を使用) ===
 
=== Apache/Nginx (Phusion Passenger を使用) ===
   
[http://www.modrails.com/ Passenger] also known as {{ic|mod_rails}} is a module available for [[Nginx]] and [[Apache]], that greatly simplifies setting up a Rails server environment. Nginx does not support modules as Apache and has to be compiled with {{ic|mod_rails}} in order to support Passenger; let Passenger compile it for you. As for Apache, let Passenger set up the module for you.
+
[http://www.modrails.com/ Passenger] (別名 {{ic|mod_rails}}) [[Nginx]] [[Apache]] で利用できるモジュールで、Rails サーバー環境のセットアップをはるかに簡単にします。Nginx Apache のようにモジュールをサポートしていないので、Passenger を使うには {{ic|mod_rails}} でコンパイルする必要があります。Passenger が勝手にコンパイルをおこなってくれます。Apache の場合、Passenger がモジュールの設定をしてくれます。
   
  +
まずは 'passenger' の gem をインストール:
{{note|The current Nginx package in the official repositories actually is compiled with the Passenger module, so you can install it via pacman. The configuration files are stored in {{ic|/etc/nginx/conf/}}.}}
 
{{note|As of 2013-10-07 this doesn't seem to be the case any longer and you will have to follow the remaining steps here}}
 
 
Start by installing the 'passenger' gem:
 
 
# gem install passenger
 
# gem install passenger
   
  +
[[Apache]] を使用する場合、以下を実行:
If you are aiming to use [[Apache]], run:
 
 
# passenger-install-apache2-module
 
# passenger-install-apache2-module
   
In case a rails application is deployed with a sub-URI, like http://example.com/yourapplication, some additional configuration is required, see [http://www.modrails.com/documentation/Users%20guide%20Apache.html#deploying_rails_to_sub_uri the modrails documentation]
+
http://example.com/yourapplication のように、sub-URI rails アプリケーションをデプロイする場合、追加設定が必要になります。[http://www.modrails.com/documentation/Users%20guide%20Apache.html#deploying_rails_to_sub_uri modrails のドキュメント] を見て下さい。
   
For [[Nginx]]:
+
[[Nginx]] の場合:
 
# passenger-install-nginx-module
 
# passenger-install-nginx-module
   
  +
インストーラはインストールに関する追加情報を出力します (インストールする追加ライブラリなど)。
The installer will provide you with any additional information regarding the installation (such as installing additional libraries).
 
   
  +
Nginx でアプリケーションを表示するには、以下のように設定:
To serve an application with Nginx, configure it as follows:
 
 
<pre>
 
<pre>
 
server {
 
server {
198行目: 179行目:
 
}
 
}
 
</pre>
 
</pre>
  +
  +
=== Puma (Nginx をリバースプロキシサーバーとして使用) ===
  +
  +
[http://puma.io/ Puma] ([https://github.com/puma/puma Github ページ]) は Ruby/Rack アプリケーションのためのシンプル・高速・並列動作の HTTP 1.1 サーバーで、Webrick や Mongrel を置き換えることを目指しています。Rubinius の go-to サーバーとして設計されているだけでなく、JRuby や MRI とも上手く動作します。リバースプロキシサーバーはロードバランサとして機能し、外部リクエストをウェブアプリのプールに振り分けます。
  +
  +
ウェブサーバーはサーバー用のユーザーとグループで使うのが良いので、[[ユーザーとグループ#ユーザーを追加する例]]を見て下さい。以下ではユーザー名として {{ic|rails}} を、グループ名として {{ic|server}} を、rails のアプリ名として {{ic|my_app}} を使います。
  +
  +
まずは {{ic|/var/www/my_app}} にあなたのアプリをコピーしてください。そして以下のコマンドで所有者を設定します:
  +
# cd /var/www/
  +
# chown -R rails:server my_app
  +
  +
そして、次のコマンドでパーミッションを設定:
  +
# chmod -R 775 my_app
  +
  +
次に Gemfile に {{ic|puma gem}} を追加してインストール:
  +
$ cd my_app
  +
$ bundle install
  +
  +
また、pacman で {{ic|nginx}} をインストールしてください。
  +
  +
アプリフォルダに以下のコマンドで sockets, pids, log フォルダを作成:
  +
$ mkdir -p shared/pids shared/sockets shared/log
  +
  +
{{ic|nginx.conf}} をバックアップ:
  +
# cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup
  +
  +
お好きなエディタで nginx.conf ファイルを新しく作成して以下のコードをコピー、自由に編集してください:
  +
<pre>
  +
#user html;
  +
worker_processes 1; # this may connect with the worker numbers puma can use.
  +
  +
#error_log logs/error.log;
  +
#error_log logs/error.log notice;
  +
#error_log logs/error.log info;
  +
  +
#pid logs/nginx.pid;
  +
  +
  +
events {
  +
worker_connections 1024;
  +
}
  +
  +
http {
  +
upstream app {
  +
# Path to Puma SOCK file, as defined previously
  +
server unix:/var/www/my_app/shared/sockets/puma.sock;
  +
}
  +
  +
server {
  +
listen 80;
  +
server_name localhost; # or your server name
  +
  +
root /var/www/my_app/public;
  +
  +
try_files $uri/index.html $uri @app;
  +
  +
location @app {
  +
proxy_pass http://app;
  +
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  +
proxy_set_header Host $http_host;
  +
proxy_redirect off;
  +
}
  +
  +
error_page 500 502 503 504 /500.html;
  +
client_max_body_size 4G;
  +
keepalive_timeout 10;
  +
}
  +
}</pre>
  +
  +
{{ic|nginx}} サービスを起動してください。
  +
  +
puma サーバーを起動する方法は複数存在します。以下では2つの方法を推奨しています:
  +
  +
どちらの方法にしても、{{ic|config/puma.rb}} ファイルを作成して以下のコードをコピーしてください。そして必要に応じて修正を加えます:
  +
<pre>
  +
# Change to match your CPU core count
  +
# You can check available worker numbers with $ grep -c processor /proc/cpuinfo
  +
# also see the comment in the nginx.conf
  +
workers 2
  +
  +
# Min and Max threads per worker
  +
#threads 1, 6
  +
  +
app_dir = File.expand_path("../..", __FILE__)
  +
shared_dir = "#{app_dir}/shared"
  +
  +
# Default to production
  +
#rails_env = ENV['RAILS_ENV'] || "production"
  +
#environment rails_env
  +
  +
# Set up socket location
  +
bind "unix://#{shared_dir}/sockets/puma.sock"
  +
  +
# Logging
  +
#stdout_redirect "#{shared_dir}/log/puma.stdout.log", "#{shared_dir}/log/puma.stderr.log", true
  +
  +
# Set master PID and state locations
  +
pidfile "#{shared_dir}/pids/puma.pid"
  +
#state_path "#{shared_dir}/pids/puma.state"
  +
#activate_control_app
  +
  +
#on_worker_boot do
  +
# require "active_record"
  +
# ActiveRecord::Base.connection.disconnect! rescue ActiveRecord::ConnectionNotEstablished
  +
# ActiveRecord::Base.establish_connection(YAML.load_file("#{app_dir}/config/database.yml")[rails_env])
  +
#end</pre>
  +
  +
==== 選択肢 A: 設定ファイルを使う ====
  +
  +
次のコマンドでサーバーを起動:
  +
$ bundle exec puma -C config/puma.rb
  +
  +
{{ic|-d}} パラメータを使うことでバックグラウンドで起動することもできます。{{ic|kill}} したくなったら以下で確認してください:
  +
$ pgrep puma
  +
  +
ログアウトしても実行し続けるには、以下を使います:
  +
$ nohup bundle exec puma -C config/puma.rb &
  +
ただしシステムを再起動すると、プロセスは消失します。
  +
  +
==== 選択肢 B: systemd を使う ====
  +
  +
systemd ユニットを[[作成]]します。
  +
  +
{{hc|~/.config/systemd/user/puma.service|2=
  +
[Unit]
  +
Description=Puma application server
  +
After=network.target
  +
  +
[Service]
  +
WorkingDirectory=/var/www/my_app
  +
#Environment=RAILS_ENV=production
  +
PIDFile=/var/www/my_app/shared/pids/puma.pid
  +
ExecStart=/home/rails/.gem/ruby/2.2.0/bin/bundle exec \
  +
/home/rails/.gem/ruby/2.2.0/bin/puma \
  +
-C /var/www/my_app/config/puma.rb
  +
  +
[Install]
  +
WantedBy=default.target
  +
}}
  +
  +
そして、{{ic|puma.service}} ユーザーユニットを[[起動]]します。
  +
  +
puma をシステム全体で有効にするには、以下を[[作成]]します。
  +
  +
{{hc|/etc/systemd/system/puma.service|2=
  +
[Unit]
  +
Description=Puma application server
  +
After=network.target
  +
  +
[Service]
  +
WorkingDirectory=/var/www/my_app
  +
#Environment=RAILS_ENV=production
  +
User=rails
  +
PIDFile=/var/www/my_app/shared/pids/puma.pid
  +
ExecStart=/home/rails/.gem/ruby/2.2.0/bin/bundle exec \
  +
/home/rails/.gem/ruby/2.2.0/bin/puma \
  +
-C /var/www/my_app/config/puma.rb
  +
  +
[Install]
  +
WantedBy=multi-user.target}}
  +
  +
詳しくは [[#参照]] を見て下さい。また、[https://github.com/capistrano/capistrano capistrano] を使えばプロダクションモードで簡単にアプリをデプロイすることができます。
   
 
== データベース ==
 
== データベース ==
   
  +
ほとんどの Web アプリケーションは、ある種のデータベースと対話する必要があります。 ActiveRecord(Rails がデータベース抽象化を提供するために使用する ORM )は、MySQL、SQLite、および PostgreSQL で最も人気のあるいくつかのデータベースベンダーをサポートしています。次に、データベースに接続できる Rails アプリケーション Web サイトのファイル ''config /database.yml'' を構成する必要があります。
Most web applications will need to interact with some sort of database. ActiveRecord (the ORM used by Rails to provide database abstraction) supports several database vendors, the most popular of which are MySQL, SQLite, and PostgreSQL.
 
   
 
=== SQLite ===
 
=== SQLite ===
   
  +
SQLite は Ruby on Rails のデフォルトの軽量データーベースです。SQLite を使用するには、{{Pkg|sqlite}} をインストールしてください。
SQLite is the default lightweight database for Ruby on Rails. To enable SQLite, simply install {{Pkg|sqlite}}.
 
   
 
=== PostgreSQL ===
 
=== PostgreSQL ===
   
{{Pkg|postgresql}} をインストールしてください
+
{{Pkg|postgresql}} をインストールします
  +
  +
Rails 用にインストールします。
  +
# gem install pg
  +
  +
または、プロジェクトの Gemfile に gem を追加し、bundle を使用します。
  +
  +
新しい Rails の Web サイトを作成します。
  +
# rails new my_web_site -d postgresql
   
 
=== MySQL ===
 
=== MySQL ===
   
  +
まず、MySQL サーバーをインストールし、設定します。この方法については [[MariaDB]] を参照してください。
First, install and configure a MySQL server. Please refer to [[MySQL]] on how to do this.
 
   
  +
ネイティブの拡張機能を持つ gem が必要です。root でインストールするのがベストでしょう。
A gem with some native extensions is required, probably best installed as root:
 
 
# gem install mysql
 
# gem install mysql
   
  +
パラメータ {{ic|-d}} を使用することで、MySQL 用に設定された rails アプリケーションを生成することができます。
You can generate a rails application configured for MySQL by using the {{ic|-d}} parameter:
 
 
$ rails new testapp_name -d mysql
 
$ rails new testapp_name -d mysql
   
  +
=== データベースアクセス設定 ===
You then need to edit {{ic|config/database.yml}}. Rails uses different databases for development, testing, production and other environments. Here is an example development configuration for MySQL running on localhost:
 
   
  +
どのデータベース (MySQL, Postgresql, SQlite (デフォルト)) を使用する場合でも、{{ic|config/database.yml}} を編集する必要があります。Rails は、開発環境、テスト環境、本番環境、その他の環境で異なるデータベースを使用します。以下は、localhost で動作する MySQL の開発用設定例です。
development:
 
  +
adapter: mysql
 
  +
default:
database: my_application_database
 
  +
adapter: mysql (or postgresql or sqlite)
username: development
 
  +
username: my_user_name_access
 
password: my_secret_password
 
password: my_secret_password
   
  +
安全上の理由から、パスワードを直接テキストファイルに平文で書き込まないのがよい方法です。
Note that you do not have to actually create the database using MySQL, as this can be done via Rails with:
 
  +
その代わりに、"my_secret_password" を "'<%= ENV["MYSQL_PASSWD"] %>'" で置き換えることができます。ここで MYSQL_PASSWD は、サーバーが使用するユーザー環境 (~/.profile または ~/.bashrc または ~/.zshrc) からエクスポートした環境変数で、あなたの選択と ユーティリティによって決定される。<%= ENV....で囲んでください。パスワードに # や ! などの特殊文字が含まれている場合は、"'" で囲んで検索してください。
  +
  +
=== Rails からデータベースを作成する ===
  +
  +
なお、実際に MySQL や Postgresql、Sqlite を使ってデータベースを作成する必要はなく、Rails から直接行うことができます。
  +
  +
rails-4.Xバージョンの場合。
 
# rake db:create
 
# rake db:create
   
  +
rails-5.Xバージョンの場合。
If no errors are shown, then your database has been created and Rails can talk to your MySQL database.
 
  +
# rails db:create (Rails-5.X バージョンの場合)
  +
  +
エラーが表示されなければ、データベースが作成され、Rails が MySQL データベースと対話できるようになっています。
   
 
== Rails パーフェクトセットアップ ==
 
== Rails パーフェクトセットアップ ==
   
  +
''複数のバージョンの Ruby で動作する Phusion Passenger。''
''Phusion Passenger running multiple Ruby versions.''
 
   
* [https://www.archlinux.org/ Arch Linux]: A simple, lightweight distribution. ;)
+
* [https://www.archlinux.org/ Arch Linux]: シンプル、軽量なディストリビューション。 ;)
  +
* [http://www.nginx.org/ Nginx]: 高い並行性・性能、低いメモリ使用量に注力している高速かつ軽量な'''ウェブサーバー'''。
* [http://www.nginx.org/ Nginx]: A fast and lightweight '''web server''' with a strong focus on high concurrency, performance and low memory usage.
 
* [http://www.modrails.com/ Passenger] (a.k.a. mod_rails or mod_rack): Supports both Apache and Nginx web servers. It makes deployment of Ruby web applications, such as those built on Ruby on Rails web framework, a breeze.
+
* [http://www.modrails.com/ Passenger] (別名 mod_rails または mod_rack): Apache Nginx の両方のウェブサーバーに対応。Ruby on Rails ウェブフレームワークで作られたアプリケーションなど、Ruby ウェブアプリケーションをデプロイします。
  +
* [https://rvm.io/ Ruby Version Manager] (RVM): インタプリタから gem セットまで複数の Ruby 環境を簡単にインストール・管理・作業することができるコマンドラインツール。RVM は完全に自己完結した専用環境でプロジェクトをデプロイします。特定バージョンの Ruby から、アプリケーションを実行するのに必要な gem の正確なセットまで。
* [https://rvm.io/ Ruby Version Manager] (RVM): A command-line tool which allows you to easily install, manage, and work with multiple Ruby environments from interpreters to sets of gems. RVM lets you deploy each project with its own completely self-contained and dedicated environment —from the specific version of ruby, all the way down to the precise set of required gems to run your application—.
 
* [http://sqlite.org/ SQLite]: The default lightweight '''database''' for Ruby on Rails.
+
* [http://sqlite.org/ SQLite]: Ruby on Rails のデフォルト、軽量な'''データベース'''
   
 
=== ステップ 0: SQLite ===
 
=== ステップ 0: SQLite ===
   
Install {{Pkg|sqlite}}.
+
{{Pkg|sqlite}} をインストールします。
   
{{note|Of course SQLite is not critical in this setup, you can use MySQL and PostgreSQL as well.}}
+
{{note|もちろん SQLite は必須ではありません。MySQL PostgreSQL を使うことだってできます。}}
   
 
=== ステップ 1: RVM ===
 
=== ステップ 1: RVM ===
   
  +
[[RVM#マルチユーザーインストール|こちら]]に書かれているように [[RVM]] をマルチユーザーインストールしてください。
Make a multi-user [[RVM]] installation as specified [[RVM#Multi-user_installation|here]].
 
   
  +
'ユーザーを rvm グループに追加'のステップでは、以下を実行:
In the 'adding users to the rvm group' step, do
 
 
# usermod -a -G rvm http
 
# usermod -a -G rvm http
 
# usermod -a -G rvm nobody
 
# usermod -a -G rvm nobody
   
{{ic|http}} and {{ic|nobody}} are the users related to Nginx and Passenger, respectively.
+
{{ic|http}} {{ic|nobody}} はそれぞれ Nginx Passenger に関連するユーザーです。
   
  +
{{note|'nobody' ユーザーを 'rvm' グループに追加するのは必要ないかもしれません。}}
{{note|Maybe adding the 'nobody' user to the 'rvm' group is not necessary.}}
 
   
 
=== ステップ 2: Ruby ===
 
=== ステップ 2: Ruby ===
   
  +
RVM をインストールできたら、最新の Ruby インタプリタをインストールします:
Once you have a working RVM installation in your hands, it is time to install the latest Ruby interpreter
 
  +
{{Note|Ruby のインストール時にパッチが適用されます。先に {{ic|base-devel}} グループをインストールしておいてください。}}
{{Note|During the installation of Ruby patches will be applied. Consider installing the {{ic|base-devel}} group beforehand.}}
 
   
 
$ rvm install 2.0.0
 
$ rvm install 2.0.0
   
{{Note| It may be useful to delete the 'global' gemsets of the environments that have web applications. Their gems might somehow interfere with Passenger. In that case, a {{ic|rvm 2.0.0 do gemset delete global}} is sufficient.}}
+
{{Note| ウェブアプリケーションがある環境の ''グローバル'' gem セットを削除すると便利な場合があります。その gems は何らかの形で Passenger の邪魔をするかもしれません。この場合、{{ic|rvm 2.0.0 do gemset delete global}} で十分です。}}
   
 
=== ステップ 3: Nginx と Passenger ===
 
=== ステップ 3: Nginx と Passenger ===
   
Run the following to allow passenger install nginx:
+
以下を実行して passenger nginx をインストール:
 
$ rvm use 2.0.0
 
$ rvm use 2.0.0
 
$ gem install passenger
 
$ gem install passenger
 
$ rvmsudo passenger-install-nginx-module
 
$ rvmsudo passenger-install-nginx-module
   
The passenger gem will be put into the ''default'' gemset.
+
passenger gem ''default'' gemset に追加されます。
   
  +
Nginx のソースがダウンロードされて、コンパイル・インストールされます。Nginx のデフォルトインストール先は {{ic|/opt/nginx}} になります。
This will download the sources of Nginx, compile and install it for you. It will guide you through all the process. Note that the default location for Nginx will be {{ic|/opt/nginx}}.
 
   
{{Note|If you encounter a compilation error regarding Boost threads, see [https://bbs.archlinux.org/viewtopic.php?id&#61;139164 this] article.}}
+
{{Note|Boost スレッドに関するコンパイルエラーが発生した場合は、[https://bbs.archlinux.org/viewtopic.php?id&#61;139164 この] 記事を参照してください。}}
   
After completion, add the following two lines into the 'http block' at {{ic|/opt/nginx/conf/nginx.conf}} that look like:
+
完了したら {{ic|/opt/nginx/conf/nginx.conf}} に以下のように http ブロックを追加してください:
   
 
http {
 
http {
293行目: 455行目:
 
}
 
}
   
  +
{{Note|このステップは現在、インストーラースクリプトによって自動的に実行されています。}}
{{Note|This step is currently being done automatically by the installer script.}}
 
   
 
=== ステップ 4: Gemsets と Apps ===
 
=== ステップ 4: Gemsets と Apps ===
   
For each Rails application you should have a gemset. Suppose that you want to try [http://refinerycms.com RefineryCMS] against [http://www.browsercms.org BrowserCMS], two open-source Content Management Systems based on Rails.
+
Rails アプリケーションごとに、gemset を用意する必要があります。例えば、[http://refinerycms.com RefineryCMS] [http://www.browsercms.org BrowserCMS] という Rails ベースの2つのオープンソースコンテンツマネジメントシステムを試してみようとします。
   
Install RefineryCMS first:
+
まず RefineryCMS をインストール:
   
 
$ rvm use 2.0.0@refinery --create
 
$ rvm use 2.0.0@refinery --create
306行目: 468行目:
 
$ gem install refinerycms refinerycms-i18n sqlite3
 
$ gem install refinerycms refinerycms-i18n sqlite3
   
  +
''refineria'' という名前で RefineryCMS インスタンスをデプロイ:
Deploy a RefineryCMS instance called ''refineria'':
 
   
 
$ cd /srv/http/
 
$ cd /srv/http/
 
$ rvmsudo refinerycms refineria
 
$ rvmsudo refinerycms refineria
   
  +
別の gemset に BrowserCMS をインストール:
Install BrowserCMS in a different gemset:
 
   
 
$ rvm use 2.0.0@browser --create
 
$ rvm use 2.0.0@browser --create
318行目: 480行目:
 
$ gem install browsercms sqlite3
 
$ gem install browsercms sqlite3
   
  +
''navegador'' という名前で BrowserCMS インスタンスをデプロイ:
Deploy a BrowserCMS instance called ''navegador'':
 
   
 
$ cd /srv/http/
 
$ cd /srv/http/
325行目: 487行目:
 
$ rvmsudo rake db:install
 
$ rvmsudo rake db:install
   
=== Passenger for Nginx and Passenger Standalone ===
+
=== Passenger for Nginx Passenger Standalone ===
   
  +
Passenger アイテムが3回、異なる意図でインストールされたことをご覧ください。
Observe that the passenger gem was installed three times and with different intentions; in the environments
 
 
* ''2.0.0'' => for Nginx,
 
* ''2.0.0'' => for Nginx,
 
* ''2.0.0@refinery'' => Standalone
 
* ''2.0.0@refinery'' => Standalone
 
* ''2.0.0@browser'' => Standalone
 
* ''2.0.0@browser'' => Standalone
   
  +
Passenger for Nginx と Passenger Standalone を組み合わせる作戦です。まず、最もよく使う Ruby 環境(インタープリタと gemset)を特定する必要があります。この設定では、Ruby インタープリタとデフォルトの gemset が選択されています。その環境を利用するために、Passenger for Nginx の設定を行います(ステップ3)
The strategy is to combine Passenger for Nginx with Passenger Standalone. One must first identify the Ruby environment (interpreter plus gemset) that one uses the most; in this setup the Ruby interpreter and the default gemset were selected. One then proceeds with setting up Passenger for Nginx to use that environment (step 3).
 
  +
* 選択した環境内のアプリケーションは、本記事の [[Ruby on Rails#Apache/Nginx (Phusion Passenger を使用)|Apache/Nginx (Phusion Passenger を使用))]] と同様に提供することが可能です。
* Applications within the chosen environment can be served as in [[Ruby_on_Rails#Apache.2FNginx_.28using_Phusion_Passenger.29|Apache/Nginx (using Phusion Passenger)]], page up in this article.
 
  +
* 異なる Ruby バージョンや gemset を使用するアプリケーションは、Passenger Standalone を通して個別に提供し、リバースプロキシ設定(ステップ6)によりメインの Web サーバーに接続することができます。
* All applications that are to use a different Ruby version and/or gemset can be served separately through Passenger Standalone and hook into the main web server via a reverse proxy configuration (step 6).
 
   
 
=== ステップ 5: .rvmrc ファイルと所有者 ===
 
=== ステップ 5: .rvmrc ファイルと所有者 ===
   
  +
このステップは、セットアップの正しい動作のために非常に重要です。RVM はフォルダーを変更する際に .rvmrc ファイルを探し、見つかれば読み込みます。このファイルには通常、次のような行を記述します。
This step is crucial for the correct behaviour of the setup. RVM seeks for .rvmrc files when changing folders; if it finds one, it reads it. In these files normally one stores a line like
 
rvm <ruby_version>@<gemset_name>
+
rvm <ruby_version>@<gemset_name> です。
  +
アプリケーションのルートフォルダの入り口に、指定された環境が設定されるようになります。
so the specified environment is set at the entrance of applications' root folder.
 
   
Create /srv/http/refineria/.rvmrc doing
+
{{ic|/srv/http/refineria/.rvmrc}} を作成:
 
# echo "rvm ree@refinery" > /srv/http/refineria/.rvmrc
 
# echo "rvm ree@refinery" > /srv/http/refineria/.rvmrc
, and /srv/http/navegador/.rvmrc with
+
{{ic|/srv/http/navegador/.rvmrc}} を作成:
 
# echo "rvm 2.0.0@browser" > /srv/http/navegador/.rvmrc
 
# echo "rvm 2.0.0@browser" > /srv/http/navegador/.rvmrc
  +
RVM が .rvmrc を見つけるたびに、与えられたファイルを信頼するかどうか尋ねられるので、今作成した2つのファイルを確認する必要があります。
You have to enter to both application root folders now, because every first time that RVM finds a .rvmrc it asks you if you trust the given file, consequently you must validate the two files you have just created.
 
   
  +
これらのファイルは、関係するプログラムが正しい gems を見つけることを支援します。
These files aid the programs involved to find the correct gems.
 
   
  +
また、アプリケーションのファイルやフォルダの所有者が正しいユーザーでない場合、データベースの書き込みアクセスの問題に直面することになります。rvmsudo を使うと、Rails で生成されたアーカイブは ''root'' 所有になります。一方、''nobody'' は Passenger のユーザで、変更していない場合、誰が使うのか、所有する必要があるのかを、修正する必要があります。
Apart, if applications' files and folders are not owned by the right user you will face database write-access problems. The use of rvmsudo produces ''root''-owned archives when generated by Rails; in the other hand, ''nobody'' is the user for Passenger —if you have not changed it—: who will use and should posses them. Fix this doing
 
 
# chown -R nobody.nobody /srv/http/refineria /srv/http/navegador
 
# chown -R nobody.nobody /srv/http/refineria /srv/http/navegador
   
 
=== ステップ 6: リバースプロキシ ===
 
=== ステップ 6: リバースプロキシ ===
   
You have to start the Passenger Standalone web servers for your applications. So, do
+
アプリケーションの Passenger Standalone ウェブサーバーを起動してください:
 
$ cd /srv/http/refineria
 
$ cd /srv/http/refineria
 
$ rvmsudo passenger start --socket tmp/sockets/passenger.socket -d
 
$ rvmsudo passenger start --socket tmp/sockets/passenger.socket -d
  +
そして以下を実行:
and
 
 
$ cd /srv/http/navegador
 
$ cd /srv/http/navegador
 
$ rvmsudo passenger start --socket tmp/sockets/passenger.socket -d
 
$ rvmsudo passenger start --socket tmp/sockets/passenger.socket -d
  +
Passenger Standalone を始めて実行したときにインストールが実行されます。
. The first time that you run a Passenger Standalone it will perform a minor installation.
 
   
  +
一般的な ''TCP'' ソケットの代わりに ''unix ドメイン'' ソケットが使われます。unix ドメインは TCP ソケットよりも高速に動作します。
Note that you are using ''unix domain'' sockets instead of the commonly-used ''TCP'' sockets; it turns out that unix domain are significantly faster than TCP sockets.
 
   
  +
{{note|unix ソケットで問題が発生する場合、TCP に変更してください:
{{note|If you are experimenting trouble with unix sockets, changing to TCP should work:
 
 
rvmsudo passenger start -a 127.0.0.1 -p 3000 -d
 
rvmsudo passenger start -a 127.0.0.1 -p 3000 -d
 
}}
 
}}
371行目: 533行目:
 
==== システムの起動時に Passenger Standalone デーモンを起動 ====
 
==== システムの起動時に Passenger Standalone デーモンを起動 ====
   
  +
スクリプトをお持ちですか?ここに投稿してください。
''Do you have a script? Please post it here.''
 
   
The systemd script below was made for a Typo blog I host at /srv/http/typo. It's located at /etc/systemd/system/passenger_typo.service. I set the Environment= tags (see "man systemd.exec") from the output of "rvm env". The only exception was PATH=, which I had to combine from my regular PATH and the output of rvm env.
+
以下の systemd スクリプトは、私が /srv/http/typo でホストしている Typo ブログ用に作成されました。 /etc/systemd/system/passenger_typo.service にあります。 'rvmenv' の出力から Environment=tags( 'man systemd.exec' を参照)を設定しました。唯一の例外は PATH= でした。これは、通常の PATH rvmenv の出力から組み合わせる必要がありました。
   
  +
Note:"WorkingDirectory=" 変数をアプリケーションフォルダーに設定しないと、passenger はアプリを見つけることができず、その後自動的にシャットダウンします。
Note: If you don't set the "WorkingDirectory=" variable to your application folder, passenger will fail to find your app and will subsequently shut itself down.
 
   
 
<pre>
 
<pre>
408行目: 570行目:
 
==== サブドメインを使用 ====
 
==== サブドメインを使用 ====
   
Once again edit /opt/nginx/conf/nginx.conf to include some vital instructions:
+
{{ic|/opt/nginx/conf/nginx.conf}} を編集して以下のように設定:
   
 
<pre>
 
<pre>
434行目: 596行目:
 
</pre>
 
</pre>
   
  +
{{note|TCP ソケットを使用する場合 ''proxy_pass'' ディレクティブを {{ic|<nowiki>proxy_pass http://127.0.0.1:3000;</nowiki>}} のように設定してください。}}
{{note|Or if using TCP sockets, configure the ''proxy_pass'' directive like
 
<pre>proxy_pass http://127.0.0.1:3000;</pre>
 
}}
 
   
 
==== サブドメインを使用しない ====
 
==== サブドメインを使用しない ====
   
  +
何らかの理由でアプリケーションでサブドメインを使わずに {{ic|site.com/railsapp}} というような url を使いたい場合、以下のように設定することができます:
If you for some reason don't want to host each application on it's own subdomain but rather in a url like: {{ic|site.com/railsapp}} then you could do something like this in your config:
 
   
 
<pre>
 
<pre>
468行目: 628行目:
 
</pre>
 
</pre>
   
  +
{{ic|nginx}} サービスを[[起動]]すれば ''site.com/railsapp'' と ''site.com/anotherapp'' から CMS にアクセスできます。
At this point you are in conditions to run Nginx with:
 
 
# systemctl start nginx
 
 
and to access both CMSs through ''refinery.domain.com'' and ''browser.domain.com''.
 
   
 
=== 参照 ===
 
=== 参照 ===
478行目: 634行目:
 
* http://beginrescueend.com/integration/passenger
 
* http://beginrescueend.com/integration/passenger
 
* http://blog.phusion.nl/2010/09/21/phusion-passenger-running-multiple-ruby-versions
 
* http://blog.phusion.nl/2010/09/21/phusion-passenger-running-multiple-ruby-versions
  +
* http://www.ruby-journal.com/how-to-setup-rails-app-with-puma-and-nginx/
  +
* https://www.digitalocean.com/community/tutorials/how-to-deploy-a-rails-app-with-puma-and-nginx-on-ubuntu-14-04
  +
  +
== こちらも参照 ==
  +
  +
* [[Ruby]]
  +
* [[Nginx]]
  +
* [[LAMP]]
  +
* [[MySQL]]
   
 
== 参照 ==
 
== 参照 ==
   
* Ruby on Rails http://rubyonrails.org/download.
+
* [https://rubyonrails.org/ 公式サイト]
  +
* Mongrel http://mongrel.rubyforge.org.
 
  +
{{TranslationStatus|Ruby on Rails|2022/6/3|720835}}

2022年6月3日 (金) 14:01時点における最新版

関連記事

Ruby on Rails (よく Rails とか RoR と略されます) は Ruby プログラミング言語によるオープンソースのウェブアプリケーションフレームワークです。Rails はウェブ開発者によって高速な開発のために使用されているアジャイル開発で使われるように出来ています。

このドキュメントでは Arch Linux システムで Ruby on Rails フレームワークをセットアップする方法を説明します。

インストール

Ruby on Rails は まず Ruby のインストールが必要なので、インストール方法はまずその記事を読んでください。nodejs パッケージは (UglifyJS JavaScript compressor の Ruby ラッパー、オプション) を使う場合にも必要です。Rails フレームワークは Ruby のバージョン (またはシステムの Ruby インストール) にリンクされています。インストールされる Ruby のバージョンは、システム、rbenv、rvm (Ruby Version Manager) のいずれでもかまいません。

RubyGems

ノート: Gem を使ってシステム全体に Rails をインストールすることもできます。その場合、以下のコマンドを root で実行して --no-user-install を付けて下さい。root で RubyGem を使用する危険性については Ruby#gem をユーザー個別またはシステム共通でインストール を読んで下さい。

現在のユーザーで Rails をインストールするコマンド:

$ gem install rails

ドキュメントのビルドには時間がかかります。ドキュメントは不要の場合、--no-document を install コマンドに付けて下さい。

$ gem install rails --no-document

gem は Ruby モジュールのパッケージマネージャであり、Arch Linux における pacman のようなものです。gem をアップデートするには、次を実行:

$ gem update

Pacman

ruby-railsAUR パッケージを インストール します。もしくは、Ruby#pacman を使って RubyGems を管理する を見て下さい。

Quarry バイナリリポジトリ

非公式の quarry リポジトリから ruby-railsインストールしてください。

設定

Rails には WeBrick という名前のベーシックな HTTP サーバーが付属しています。テストアプリケーションを作成してテストすることができます。まず、rails コマンドでアプリケーションを作成:

$ rails new testapp_name
ノート: Errno::ENOENT: No such file or directory (...) An error occurred while installing x, and Bundler cannot continue. などのエラーが表示されたら、Bundler を設定して gem をシステム全体ではなくユーザー個別でインストールする必要があります。もしくは、root で # rails new testapp_name を一度実行してください。問題なくインストールが完了したら、testapp_name/ を削除して、$ rails new testapp_name をもう一度、通常ユーザーで実行してください。

これにより、現在の作業ディレクトリの中に新しいフォルダが作成されます。

$ cd testapp_name

次に Web サーバを起動します。デフォルトではポート3000で待ち受けます。

$ rails server

ブラウザで http://localhost:3000 を開いて、ローカルマシンの testapp_name ウェブサイトにアクセスします。

ノート: Ruby が JavaScript ランタイムを見つけられないと、表示される場合は、nodejsをインストールして下さい。

テストページが表示され、"Welcome aboard "と挨拶されるはずです。

アプリケーションサーバー

Ruby On Rails に内蔵されている HTTP サーバー (WeBrick) は開発用には便利ですが、本番環境での使用は推奨されません。#Thin, #Unicorn, Phusion Passenger などのアプリケーションサーバーを使って下さい。

Thin

Thin は高速でシンプルな Ruby ウェブサーバーです。

thin の gem をまずインストールしてください:

$ gem install thin

そして次のコマンドで起動:

$ thin start

Unicorn

Unicorn はスタンドアロンのアプリケーションサーバーで、クライアントと直接対話することはできません。その代わりに、ウェブサーバーがクライアントと Unicorn の間に入って、必要に応じてリクエストを送ります。Unicorn は基本的に Mongrel が元になっています。Unicorn は Github に使われており、リクエストを処理するのに一番適した子プロセスを出来る限り使うようなアーキテクチャになっています。Unicorn と Mongrel の違いについては こちら に説明があります。

Unicorn の gem をインストール:

# gem install unicorn

アプリケーションの設定ファイルを /etc/unicorn/ に作成。以下は Redmine の設定例です ([1] を参照):

/etc/unicorn/redmine.ru
working_directory "/srv/http/redmine"
pid "/tmp/redmine.pid"

preload_app true
timeout 60
worker_processes 4
listen 4000
stderr_path('/var/log/unicorn.log')

GC.respond_to?(:copy_on_write_friendly=) and GC.copy_on_write_friendly = true

after_fork do |server, worker|
	#start the worker on port 4000, 4001, 4002 etc...
	addr = "0.0.0.0:#{4000 + worker.nr}"
	# infinite tries to start the worker
	server.listen(addr, :tries => -1, :delay => -1, :backlog => 128)

	#Drop privileges if running as root
	worker.user('nobody', 'nobody') if Process.euid == 0
end

次のコマンドで起動:

# /usr/bin/unicorn -D -E production -c /etc/unicorn/redmine.ru

Systemd サービス

/etc/systemd/system/unicorn.service に以下を記述:

/etc/systemd/system/unicorn.service
[Unit]
Description=Unicorn application server
After=network.target

[Service]
Type=forking
User=redmine
ExecStart=/usr/bin/unicorn -D -E production -c /etc/unicorn/redmine.ru

[Install]
WantedBy=multi-user.target

これで systemctl を使って簡単に unicorn を起動・停止できます。

Nginx の設定

Nginx をセットアップしてから、以下のように unicorn を上流サーバーとして設定してください (警告: 以下は省略した例です。おそらく設定を追加しないと機能しません):

http {
	upstream unicorn {
		server 127.0.0.1:4000 fail_timeout=0;
		server 127.0.0.1:4001 fail_timeout=0;
		server 127.0.0.1:4002 fail_timeout=0;
		server 127.0.0.1:4003 fail_timeout=0;
	}

	server {
		listen		80 default;
		server_name	YOURHOSTNAMEHERE;

		location / {
			root			/srv/http/redmine/public;
			proxy_set_header	X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header Host   $http_host;
			proxy_redirect		off;
			proxy_pass		http://unicorn;
		}
	}
}

Apache/Nginx (Phusion Passenger を使用)

Passenger (別名 mod_rails) は NginxApache で利用できるモジュールで、Rails サーバー環境のセットアップをはるかに簡単にします。Nginx は Apache のようにモジュールをサポートしていないので、Passenger を使うには mod_rails でコンパイルする必要があります。Passenger が勝手にコンパイルをおこなってくれます。Apache の場合、Passenger がモジュールの設定をしてくれます。

まずは 'passenger' の gem をインストール:

# gem install passenger

Apache を使用する場合、以下を実行:

# passenger-install-apache2-module

http://example.com/yourapplication のように、sub-URI で rails アプリケーションをデプロイする場合、追加設定が必要になります。modrails のドキュメント を見て下さい。

Nginx の場合:

# passenger-install-nginx-module

インストーラはインストールに関する追加情報を出力します (インストールする追加ライブラリなど)。

Nginx でアプリケーションを表示するには、以下のように設定:

server {
    server_name app.example.org;
    root path_to_app/public; # Be sure to point to 'public' folder!
    passenger_enabled on;
    rails_env development; # Rails environment.
}

Puma (Nginx をリバースプロキシサーバーとして使用)

Puma (Github ページ) は Ruby/Rack アプリケーションのためのシンプル・高速・並列動作の HTTP 1.1 サーバーで、Webrick や Mongrel を置き換えることを目指しています。Rubinius の go-to サーバーとして設計されているだけでなく、JRuby や MRI とも上手く動作します。リバースプロキシサーバーはロードバランサとして機能し、外部リクエストをウェブアプリのプールに振り分けます。

ウェブサーバーはサーバー用のユーザーとグループで使うのが良いので、ユーザーとグループ#ユーザーを追加する例を見て下さい。以下ではユーザー名として rails を、グループ名として server を、rails のアプリ名として my_app を使います。

まずは /var/www/my_app にあなたのアプリをコピーしてください。そして以下のコマンドで所有者を設定します:

# cd /var/www/
# chown -R rails:server my_app

そして、次のコマンドでパーミッションを設定:

# chmod -R 775 my_app

次に Gemfile に puma gem を追加してインストール:

$ cd my_app 
$ bundle install

また、pacman で nginx をインストールしてください。

アプリフォルダに以下のコマンドで sockets, pids, log フォルダを作成:

$ mkdir -p shared/pids shared/sockets shared/log

nginx.conf をバックアップ:

# cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup

お好きなエディタで nginx.conf ファイルを新しく作成して以下のコードをコピー、自由に編集してください:

#user html;
worker_processes  1; # this may connect with the worker numbers puma can use.

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}

http {
	upstream app {
	    # Path to Puma SOCK file, as defined previously
 	    server unix:/var/www/my_app/shared/sockets/puma.sock;
	}

	server {
	    listen 80;
	    server_name localhost; # or your server name

	    root /var/www/my_app/public;

	    try_files $uri/index.html $uri @app;

	    location @app {
		proxy_pass http://app;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_set_header Host $http_host;
		proxy_redirect off;
	    }

	    error_page 500 502 503 504 /500.html;
	    client_max_body_size 4G;
	    keepalive_timeout 10;
	}
}

nginx サービスを起動してください。

puma サーバーを起動する方法は複数存在します。以下では2つの方法を推奨しています:

どちらの方法にしても、config/puma.rb ファイルを作成して以下のコードをコピーしてください。そして必要に応じて修正を加えます:

# Change to match your CPU core count
# You can check available worker numbers with $ grep -c processor /proc/cpuinfo
# also see the comment in the nginx.conf
workers 2

# Min and Max threads per worker
#threads 1, 6

app_dir = File.expand_path("../..", __FILE__)
shared_dir = "#{app_dir}/shared"

# Default to production
#rails_env = ENV['RAILS_ENV'] || "production"
#environment rails_env

# Set up socket location
bind "unix://#{shared_dir}/sockets/puma.sock"

# Logging
#stdout_redirect "#{shared_dir}/log/puma.stdout.log", "#{shared_dir}/log/puma.stderr.log", true

# Set master PID and state locations
pidfile "#{shared_dir}/pids/puma.pid"
#state_path "#{shared_dir}/pids/puma.state"
#activate_control_app

#on_worker_boot do
#  require "active_record"
#  ActiveRecord::Base.connection.disconnect! rescue ActiveRecord::ConnectionNotEstablished
#  ActiveRecord::Base.establish_connection(YAML.load_file("#{app_dir}/config/database.yml")[rails_env])
#end

選択肢 A: 設定ファイルを使う

次のコマンドでサーバーを起動:

$ bundle exec puma -C config/puma.rb

-d パラメータを使うことでバックグラウンドで起動することもできます。kill したくなったら以下で確認してください:

$ pgrep puma

ログアウトしても実行し続けるには、以下を使います:

$ nohup bundle exec puma -C config/puma.rb &

ただしシステムを再起動すると、プロセスは消失します。

選択肢 B: systemd を使う

systemd ユニットを作成します。

~/.config/systemd/user/puma.service
[Unit]
Description=Puma application server
After=network.target

[Service]
WorkingDirectory=/var/www/my_app
#Environment=RAILS_ENV=production
PIDFile=/var/www/my_app/shared/pids/puma.pid
ExecStart=/home/rails/.gem/ruby/2.2.0/bin/bundle exec \
	 /home/rails/.gem/ruby/2.2.0/bin/puma \
	 -C /var/www/my_app/config/puma.rb

[Install]
WantedBy=default.target

そして、puma.service ユーザーユニットを起動します。

puma をシステム全体で有効にするには、以下を作成します。

/etc/systemd/system/puma.service
[Unit]
Description=Puma application server
After=network.target

[Service]
WorkingDirectory=/var/www/my_app
#Environment=RAILS_ENV=production
User=rails
PIDFile=/var/www/my_app/shared/pids/puma.pid
ExecStart=/home/rails/.gem/ruby/2.2.0/bin/bundle exec \
	 /home/rails/.gem/ruby/2.2.0/bin/puma \
	 -C /var/www/my_app/config/puma.rb

[Install]
WantedBy=multi-user.target

詳しくは #参照 を見て下さい。また、capistrano を使えばプロダクションモードで簡単にアプリをデプロイすることができます。

データベース

ほとんどの Web アプリケーションは、ある種のデータベースと対話する必要があります。 ActiveRecord(Rails がデータベース抽象化を提供するために使用する ORM )は、MySQL、SQLite、および PostgreSQL で最も人気のあるいくつかのデータベースベンダーをサポートしています。次に、データベースに接続できる Rails アプリケーション Web サイトのファイル config /database.yml を構成する必要があります。

SQLite

SQLite は Ruby on Rails のデフォルトの軽量データーベースです。SQLite を使用するには、sqlite をインストールしてください。

PostgreSQL

postgresql をインストールします。

Rails 用にインストールします。

# gem install pg

または、プロジェクトの Gemfile に gem を追加し、bundle を使用します。

新しい Rails の Web サイトを作成します。

# rails new my_web_site -d postgresql

MySQL

まず、MySQL サーバーをインストールし、設定します。この方法については MariaDB を参照してください。

ネイティブの拡張機能を持つ gem が必要です。root でインストールするのがベストでしょう。

# gem install mysql

パラメータ -d を使用することで、MySQL 用に設定された rails アプリケーションを生成することができます。

$ rails new testapp_name -d mysql

データベースアクセス設定

どのデータベース (MySQL, Postgresql, SQlite (デフォルト)) を使用する場合でも、config/database.yml を編集する必要があります。Rails は、開発環境、テスト環境、本番環境、その他の環境で異なるデータベースを使用します。以下は、localhost で動作する MySQL の開発用設定例です。

 default:
   adapter: mysql (or postgresql or sqlite)
   username: my_user_name_access
   password: my_secret_password

安全上の理由から、パスワードを直接テキストファイルに平文で書き込まないのがよい方法です。 その代わりに、"my_secret_password" を "'<%= ENV["MYSQL_PASSWD"] %>'" で置き換えることができます。ここで MYSQL_PASSWD は、サーバーが使用するユーザー環境 (~/.profile または ~/.bashrc または ~/.zshrc) からエクスポートした環境変数で、あなたの選択と ユーティリティによって決定される。<%= ENV....で囲んでください。パスワードに # や ! などの特殊文字が含まれている場合は、"'" で囲んで検索してください。

Rails からデータベースを作成する

なお、実際に MySQL や Postgresql、Sqlite を使ってデータベースを作成する必要はなく、Rails から直接行うことができます。

rails-4.Xバージョンの場合。

# rake db:create

rails-5.Xバージョンの場合。

# rails db:create (Rails-5.X バージョンの場合)

エラーが表示されなければ、データベースが作成され、Rails が MySQL データベースと対話できるようになっています。

Rails パーフェクトセットアップ

複数のバージョンの Ruby で動作する Phusion Passenger。

  • Arch Linux: シンプル、軽量なディストリビューション。 ;)
  • Nginx: 高い並行性・性能、低いメモリ使用量に注力している高速かつ軽量なウェブサーバー
  • Passenger (別名 mod_rails または mod_rack): Apache と Nginx の両方のウェブサーバーに対応。Ruby on Rails ウェブフレームワークで作られたアプリケーションなど、Ruby ウェブアプリケーションをデプロイします。
  • Ruby Version Manager (RVM): インタプリタから gem セットまで複数の Ruby 環境を簡単にインストール・管理・作業することができるコマンドラインツール。RVM は完全に自己完結した専用環境でプロジェクトをデプロイします。特定バージョンの Ruby から、アプリケーションを実行するのに必要な gem の正確なセットまで。
  • SQLite: Ruby on Rails のデフォルト、軽量なデータベース

ステップ 0: SQLite

sqlite をインストールします。

ノート: もちろん SQLite は必須ではありません。MySQL や PostgreSQL を使うことだってできます。

ステップ 1: RVM

こちらに書かれているように RVM をマルチユーザーインストールしてください。

'ユーザーを rvm グループに追加'のステップでは、以下を実行:

# usermod -a -G rvm http
# usermod -a -G rvm nobody

httpnobody はそれぞれ Nginx と Passenger に関連するユーザーです。

ノート: 'nobody' ユーザーを 'rvm' グループに追加するのは必要ないかもしれません。

ステップ 2: Ruby

RVM をインストールできたら、最新の Ruby インタプリタをインストールします:

ノート: Ruby のインストール時にパッチが適用されます。先に base-devel グループをインストールしておいてください。
$ rvm install 2.0.0
ノート: ウェブアプリケーションがある環境の グローバル gem セットを削除すると便利な場合があります。その gems は何らかの形で Passenger の邪魔をするかもしれません。この場合、rvm 2.0.0 do gemset delete global で十分です。

ステップ 3: Nginx と Passenger

以下を実行して passenger で nginx をインストール:

$ rvm use 2.0.0 
$ gem install passenger
$ rvmsudo passenger-install-nginx-module

passenger gem が default gemset に追加されます。

Nginx のソースがダウンロードされて、コンパイル・インストールされます。Nginx のデフォルトインストール先は /opt/nginx になります。

ノート: Boost スレッドに関するコンパイルエラーが発生した場合は、この 記事を参照してください。

完了したら /opt/nginx/conf/nginx.conf に以下のように http ブロックを追加してください:

http { 
  ...
  passenger_root /usr/local/rvm/gems/ruby-2.0.0-p353/gems/passenger-3.0.9;
  passenger_ruby /usr/local/rvm/wrappers/ruby-2.0.0-p353/ruby;
  ...
}
ノート: このステップは現在、インストーラースクリプトによって自動的に実行されています。

ステップ 4: Gemsets と Apps

Rails アプリケーションごとに、gemset を用意する必要があります。例えば、RefineryCMSBrowserCMS という Rails ベースの2つのオープンソースコンテンツマネジメントシステムを試してみようとします。

まず RefineryCMS をインストール:

$ rvm use 2.0.0@refinery --create
$ gem install rails -v 4.0.1
$ gem install passenger
$ gem install refinerycms refinerycms-i18n sqlite3

refineria という名前で RefineryCMS インスタンスをデプロイ:

$ cd /srv/http/
$ rvmsudo refinerycms refineria

別の gemset に BrowserCMS をインストール:

$ rvm use 2.0.0@browser --create
$ gem install rails -v 4.0.1
$ gem install passenger
$ gem install browsercms sqlite3

navegador という名前で BrowserCMS インスタンスをデプロイ:

$ cd /srv/http/
$ rvmsudo browsercms demo navegador
$ cd /srv/http/navegador
$ rvmsudo rake db:install

Passenger for Nginx と Passenger Standalone

Passenger アイテムが3回、異なる意図でインストールされたことをご覧ください。

  • 2.0.0 => for Nginx,
  • 2.0.0@refinery => Standalone
  • 2.0.0@browser => Standalone

Passenger for Nginx と Passenger Standalone を組み合わせる作戦です。まず、最もよく使う Ruby 環境(インタープリタと gemset)を特定する必要があります。この設定では、Ruby インタープリタとデフォルトの gemset が選択されています。その環境を利用するために、Passenger for Nginx の設定を行います(ステップ3)

  • 選択した環境内のアプリケーションは、本記事の Apache/Nginx (Phusion Passenger を使用)) と同様に提供することが可能です。
  • 異なる Ruby バージョンや gemset を使用するアプリケーションは、Passenger Standalone を通して個別に提供し、リバースプロキシ設定(ステップ6)によりメインの Web サーバーに接続することができます。

ステップ 5: .rvmrc ファイルと所有者

このステップは、セットアップの正しい動作のために非常に重要です。RVM はフォルダーを変更する際に .rvmrc ファイルを探し、見つかれば読み込みます。このファイルには通常、次のような行を記述します。

rvm <ruby_version>@<gemset_name> です。

アプリケーションのルートフォルダの入り口に、指定された環境が設定されるようになります。

/srv/http/refineria/.rvmrc を作成:

# echo "rvm ree@refinery" > /srv/http/refineria/.rvmrc

/srv/http/navegador/.rvmrc を作成:

# echo "rvm 2.0.0@browser" > /srv/http/navegador/.rvmrc

RVM が .rvmrc を見つけるたびに、与えられたファイルを信頼するかどうか尋ねられるので、今作成した2つのファイルを確認する必要があります。

これらのファイルは、関係するプログラムが正しい gems を見つけることを支援します。

また、アプリケーションのファイルやフォルダの所有者が正しいユーザーでない場合、データベースの書き込みアクセスの問題に直面することになります。rvmsudo を使うと、Rails で生成されたアーカイブは root 所有になります。一方、nobody は Passenger のユーザで、変更していない場合、誰が使うのか、所有する必要があるのかを、修正する必要があります。

# chown -R nobody.nobody /srv/http/refineria /srv/http/navegador

ステップ 6: リバースプロキシ

アプリケーションの Passenger Standalone ウェブサーバーを起動してください:

$ cd /srv/http/refineria
$ rvmsudo passenger start --socket tmp/sockets/passenger.socket -d

そして以下を実行:

$ cd /srv/http/navegador
$ rvmsudo passenger start --socket tmp/sockets/passenger.socket -d

Passenger Standalone を始めて実行したときにインストールが実行されます。

一般的な TCP ソケットの代わりに unix ドメイン ソケットが使われます。unix ドメインは TCP ソケットよりも高速に動作します。

ノート: unix ソケットで問題が発生する場合、TCP に変更してください:
rvmsudo passenger start -a 127.0.0.1 -p 3000 -d

システムの起動時に Passenger Standalone デーモンを起動

スクリプトをお持ちですか?ここに投稿してください。

以下の systemd スクリプトは、私が /srv/http/typo でホストしている Typo ブログ用に作成されました。 /etc/systemd/system/passenger_typo.service にあります。 'rvmenv' の出力から Environment=tags( 'man systemd.exec' を参照)を設定しました。唯一の例外は PATH= でした。これは、通常の PATH と rvmenv の出力から組み合わせる必要がありました。

Note:"WorkingDirectory=" 変数をアプリケーションフォルダーに設定しないと、passenger はアプリを見つけることができず、その後自動的にシャットダウンします。

[Unit]
Description=Passenger Standalone Script for Typo
After=network.target

[Service]
Type=forking
WorkingDirectory=/srv/http/typo
PIDFile=/srv/http/typo/tmp/pids/passenger.pid

Environment=PATH=/usr/local/rvm/gems/ruby-2.0.0-p0@typo/bin:/usr/local/rvm/gems/ruby-2.0.0-p0@global/bin:/usr/local/rvm/rubies/ruby-2.0.0-p0/bin:/usr/local/rvm/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/bin/core_perl
Environment=rvm_env_string=ruby-2.0.0-p0@typo
Environment=rvm_path=/usr/local/rvm
Environment=rvm_ruby_string=ruby-2.0.0-p0
Environment=rvm_gemset_name=typo
Environment=RUBY_VERSION=ruby-2.0.0-p0
Environment=GEM_HOME=/usr/local/rvm/gems/ruby-2.0.0-p0@typo
Environment=GEM_PATH=/usr/local/rvm/gems/ruby-2.0.0-p0@typo:/usr/local/rvm/gems/ruby-2.0.0-p0@global
Environment=MY_RUBY_HOME=/usr/local/rvm/rubies/ruby-2.0.0-p0
Environment=IRBRC=/usr/local/rvm/rubies/ruby-2.0.0-p0/.irbrc

ExecStart=/bin/bash -c "rvmsudo passenger start --socket /srv/http/typo/tmp/sockets/passenger.socket -d"

[Install]
WantedBy=multi-user.target

ステップ 7: デプロイメント

サブドメインを使用

/opt/nginx/conf/nginx.conf を編集して以下のように設定:

## RefineryCMS ##

server {
    server_name refinery.domain.com;
    root /srv/http/refineria/public;
    location / {
        proxy_pass http://unix:/srv/http/refineria/tmp/sockets/passenger.socket;
        proxy_set_header Host $host;
    }
}

## BrowserCMS ##

server {
    server_name browser.domain.com;
    root /srv/http/navegador/public;
    location / {
        proxy_pass http://unix:/srv/http/navegador/tmp/sockets/passenger.socket;
        proxy_set_header Host $host;
    }
}
ノート: TCP ソケットを使用する場合 proxy_pass ディレクティブを proxy_pass http://127.0.0.1:3000; のように設定してください。

サブドメインを使用しない

何らかの理由でアプリケーションでサブドメインを使わずに site.com/railsapp というような url を使いたい場合、以下のように設定することができます:

server {
    server_name site.com;
    #Base for the html files etc
    root /srv/http/;

    #First application you want hosted under domain site.com/railsapp
    location /railsapp {
        root /srv/http/railsapp/public;
        #you may need to change passenger_base_uri to be the uri you want to point at, ie:
        #passenger_base_uri /railsapp;
        #but probably only if you're using the other solution with passenger phusion
        proxy_pass http://unix:/srv/http/railsapp/tmp/sockets/passenger.socket;
        proxy_set_header Host $host;
    }

    #Second applicatino you want hosted under domain site.com/anotherapp
    location /anotherapp {
        root /srv/http/anotherapp/public;
        #same thing about the passenger_base_uri here, but with value /anotherapp instead
        proxy_pass http://unix:/srv/http/anotherapp/tmp/sockets/passenger.socket;
        proxy_set_header Host $host;
    }
}

nginx サービスを起動すれば site.com/railsappsite.com/anotherapp から CMS にアクセスできます。

参照

こちらも参照

参照

翻訳ステータス: このページは en:Ruby on Rails の翻訳バージョンです。最後の翻訳日は 2022/6/3 です。もし英語版に 変更 があれば、翻訳の同期を手伝うことができます。