LoginSignup
2

More than 5 years have passed since last update.

【修正済み】Rails 5.1.0 から rails server の -p オプションより環境変数 PORT が優先される模様

Last updated at Posted at 2017-05-01

注) 2017/05/02 現在、コマンドライン引数を優先する PR が master ブランチにマージされました。

時間ができたので、とあるプロダクトの Rails を 5.1.0 にアップデートして試験を始めようとしている今日この頃です。

テストのために foreman を使って各種プロセスを立ち上げたところ、なぜか API サーバに繋がりません。ログをよくよく見てみると、listen しているポートが期待通りではありませんでした。ある事情から、API サーバは foreman が用意してくれるポート番号を使わず、固定のポート番号を使っているのですが、そのポート番号指定が無視されています。

以下の通り、環境変数 PORT をセットしている状態で rails server のポート引数 -p を与えても無視されます。

$ rails --version
Rails 5.1.0
$ export PORT=3456
$ echo $PORT
3456
$ rails s -p 3333
=> Booting WEBrick
=> Rails 5.1.0 application starting in development on http://localhost:3456
=> Run `rails server -h` for more startup options
[2017-05-01 16:09:44] INFO  WEBrick 1.3.1
[2017-05-01 16:09:44] INFO  ruby 2.4.1 (2017-03-22) [x86_64-darwin16]
[2017-05-01 16:09:44] INFO  WEBrick::HTTPServer#start: pid=37581 port=3456

Rails 5.0.2 ではコマンドライン引数が優先されています。

$ rails --version
Rails 5.0.2
$ echo $PORT
3456
$ rails s -p 3333
=> Booting WEBrick
=> Rails 5.0.2 application starting in development on http://localhost:3333
=> Run `rails server -h` for more startup options
[2017-05-01 16:11:24] INFO  WEBrick 1.3.1
[2017-05-01 16:11:24] INFO  ruby 2.4.1 (2017-03-22) [x86_64-darwin16]
[2017-05-01 16:11:24] INFO  WEBrick::HTTPServer#start: pid=43415 port=3333
$ rails s
=> Booting WEBrick
=> Rails 5.0.2 application starting in development on http://localhost:3456
=> Run `rails server -h` for more startup options
[2017-05-01 16:11:40] INFO  WEBrick 1.3.1
[2017-05-01 16:11:40] INFO  ruby 2.4.1 (2017-03-22) [x86_64-darwin16]
[2017-05-01 16:11:40] INFO  WEBrick::HTTPServer#start: pid=44602 port=3456

ざっくりコードを眺めた限り、以下の通り環境変数を優先している様に見えます。

railties/lib/rails/commands/server/server_command.rb
# https://github.com/rails/rails/blob/master/railties/lib/rails/commands/server/server_command.rb#L186-L188

        def port
          ENV.fetch("PORT", options[:port]).to_i
        end

一方で、バインドするアドレスについてはコマンドライン引数を優先している様に見えます。

railties/lib/rails/commands/server/server_command.rb
# https://github.com/rails/rails/blob/master/railties/lib/rails/commands/server/server_command.rb#L190-L197

        def host
          if options[:binding]
            options[:binding]
          else
            default_host = environment == "development" ? "localhost" : "0.0.0.0"
            ENV.fetch("HOST", default_host)
          end
        end

さて、Issue/PR を漁らないといけませんね。
面倒くさいのでそういうものと認識してスルーしたい気分です。

追記

細かい事は気にせず、勢いに任せて PR を作ってみました。

(修正内容以前に、ガイドラインを守れているか自信がありません…。)

2017/05/02 マージされました。

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
2