タイトル: サーバーの起動
SEOタイトル: Rails サーバーの起動 完全ガイド(rails server / rails s / -p ポート指定 / -b バインド / 環境 / Puma / 停止 / トラブル)
| この記事の要点 |
|
基本: rails server
Rails アプリの開発サーバは bin/rails server(または rails s)で起動します。プロジェクトのルートディレクトリで実行してください。
# 既定で http://localhost:3000 が立つ
bin/rails server
# 省略形
rails s
よく使うオプション
| オプション | 意味 | 例 |
|---|---|---|
-p PORT | 待受ポート(既定 3000) | rails s -p 4000 |
-b ADDRESS | バインド IP(既定 localhost) | rails s -b 0.0.0.0 |
-e ENV | 実行環境 | rails s -e production |
-d | デーモン化(バックグラウンド) | rails s -d |
-P FILE | PID ファイル位置を指定 | rails s -P tmp/pids/dev.pid |
-c FILE | Rack 設定ファイル(既定 config.ru) | rails s -c custom.ru |
外部からアクセスさせたいとき
仮想マシン / Docker / 別端末からアプリを見たい場合は -b 0.0.0.0 で全インターフェースにバインドします。あわせて Rails 6+ は config.hosts による Host ヘッダ制限があるため、開発 PC のホスト名 / IP を許可します。
# LAN の別端末から http://192.168.1.10:3000 で見たい
bin/rails server -b 0.0.0.0 -p 3000# config/environments/development.rb
Rails.application.configure do
# 開発時の Host ヘッダブロックを無効化(ローカル限定)
config.hosts.clear
# もしくは明示的に許可
# config.hosts << '192.168.1.10'
# config.hosts << /.*\.local/
end
環境を切り替える
本番設定で動かしたい場合は -e production。アセットプリコンパイル / マスタキーが必要になります。
# 本番モード
RAILS_ENV=production bin/rails server
# または
bin/rails server -e production
# 事前にアセットをコンパイル
RAILS_ENV=production bin/rails assets:precompile
裏で動いているもの: Puma
Rails 5 以降の標準アプリサーバは Puma です。rails s は内部的に Puma を起動しているだけで、config/puma.rb でワーカー数(プロセス)とスレッド数を調整できます。
# config/puma.rb
max_threads_count = ENV.fetch('RAILS_MAX_THREADS', 5)
min_threads_count = ENV.fetch('RAILS_MIN_THREADS', max_threads_count)
threads min_threads_count, max_threads_count
port ENV.fetch('PORT', 3000)
environment ENV.fetch('RAILS_ENV', 'development')
# 本番ではワーカー (マルチプロセス) を増やす
workers ENV.fetch('WEB_CONCURRENCY', 2) if ENV['RAILS_ENV'] == 'production'
preload_app!
停止と PID ファイル
停止は Ctrl + C。デーモン化したときは PID ファイルからプロセスを kill します。クラッシュ後に古い PID が残っていると「A server is already running.」と言われて起動できなくなるため、その PID ファイルを削除すれば直ります。
# 残ってしまった PID を確認
cat tmp/pids/server.pid
# 既に死んでいるプロセスなら削除して再起動
rm tmp/pids/server.pid
bin/rails server
よくあるトラブル
| 症状 | 原因 / 対処 |
|---|---|
Address already in use - bind(2) for 127.0.0.1:3000 | 別プロセスが 3000 を使用中。lsof -i:3000 で確認し kill、もしくは -p 別ポート |
A server is already running. | tmp/pids/server.pid が残存。プロセスを確認して PID ファイルを削除 |
Blocked host: example.com | Rails 6+ の Host 制限。config.hosts に追加 |
| WSL / Docker から見えない | -b 0.0.0.0 でバインド、Windows / ホスト側ファイアウォール許可 |