Rails s でportを使用していないはずなのに「Address already in use」で使用できない。

# 概要
つい最近まで問題なくrails sでローカルサーバーを起動できていたプロジェクトで「Address already in use」が表示されてサーバーが起動できなくなった。
長いコードは一部を抜き出して記述し、最後に完全なコードを記載する。

**追記**
記録として全文を残しますが、原因は単純でpuma.rbファイルにportを重複して記述していたからでした。
後書きだけをみてもらえれば事足ります。


**使用できなる前後の状況**
1. VSCodeからAtomに乗り換えた
2. ruby,rails等のアップデートはしていない
3. Gemの変更やアップデートはしていない

**動作環境**

- Ruby 2.6.3
- Rails 6.0.2.1
- puma 4.3.3

# エラーの状況

```zsh:コード1
$ rails s
=> Booting Puma
=> Rails 6.0.2.1 application starting in development
=> Run `rails server --help` for more startup options
[32206] Puma starting in cluster mode...
[32206] * Version 4.3.3 (ruby 2.6.3-p62), codename: Mysterious Traveller
[32206] * Min threads: 5, max threads: 5
[32206] * Environment: development
[32206] * Process workers: 2
[32206] * Preloading application
[32206] * Listening on tcp://127.0.0.1:3000
[32206] * Listening on tcp://[::1]:3000
Exiting
Traceback (most recent call last):
<中略>
/Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/puma-4.3.3/lib/puma/binder.rb:229:in `initialize': Address already in use - bind(2) for "127.0.0.1" port 3000 (Errno::EADDRINUSE)
```

# 試したこと
## 1.プロセスの確認
```zsh
$ ps aux | grep puma
wm               32414   0.0  0.0  4268212    376 s001  R+    5:56PM   0:00.00 grep puma
```
動いているのはgrep pumaのプロセスのみ

```zsh
$ lsof -wni tcp:3000
$
```
反応なし

## 2.ポート番号を指定して実行
```zsh
$ rails s -p 3000
=> Booting Puma
=> Rails 6.0.2.1 application starting in development
=> Run `rails server --help` for more startup options
[32461] Puma starting in cluster mode...
[32461] * Version 4.3.3 (ruby 2.6.3-p62), codename: Mysterious Traveller
[32461] * Min threads: 5, max threads: 5
[32461] * Environment: development
[32461] * Process workers: 2
[32461] * Preloading application
[32461] * Listening on tcp://127.0.0.1:3000
[32461] * Listening on tcp://[::1]:3000
[32461] Use Ctrl-C to stop
[32461] - Worker 0 (pid: 32479) booted, phase: 0
[32461] - Worker 1 (pid: 32480) booted, phase: 0
```

起動できたのでプロセスの確認

```zsh
wm@WM-Mac rails-tutorial % ps aux | grep puma
wm               32480   0.0  0.2  4497160  41452 s001  S+    6:02PM   0:00.10 puma: cluster worker 1: 32461 [rails-tutorial]
wm               32479   0.0  0.2  4498184  40716 s001  S+    6:02PM   0:00.10 puma: cluster worker 0: 32461 [rails-tutorial]
wm               32461   0.0  0.5  4452924  76132 s001  S+    6:02PM   0:01.05 puma 4.3.3 (tcp://localhost:3000) [rails-tutorial]
wm               32501   0.0  0.0  4268320    684 s000  S+    6:03PM   0:00.00 grep puma
```
cluster worker??

## 3.別プロジェクトで実行
```zsh
$ rails s
=> Booting Puma
=> Rails 6.0.2.1 application starting in development
=> Run `rails server --help` for more startup options
Puma starting in single mode...
* Version 4.3.1 (ruby 2.6.3-p62), codename: Mysterious Traveller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://127.0.0.1:3000
* Listening on tcp://[::1]:3000
Use Ctrl-C to stop
```
問題なし
プロセスの確認

```zsh
$ ps aux | grep puma
wm               32661   0.0  0.0  4268320    688 s003  S+    6:08PM   0:00.00 grep puma
wm               32631   0.0  0.4  4468552  73816 s002  S+    6:08PM   0:01.03 puma 4.3.1 (tcp://localhost:3000) [railbook]
```
pumaのみ動いている
試しにrails s -p 3000で実行してもpumaのみが動作していた
もう一つ別のプロジェクトでも試してみたが同様に問題なし
cluster workerが問題なのか？

## 4.pumaのバージョン変更
問題なく起動できたプロジェクトに合わせてpumaのバージョンを4.1に変更するも同様のエラー
エラー最終行のpuma/binder.rb:229がpuma/binder.rb:283に変わっていたので中身をみてみると全く同じ内容だったがよく分からないのでとりあえず放置（コード2）

## 5.プロジェクトの/config/puma.rbを変更
起動できないプロジェクトのコード（コード3）を起動できているプロジェクト（コード4）で上書きすると起動できた
プロセスの確認

```zsh
$ ps aux | grep puma
wm               33059   0.0  0.4  4450988  74956 s001  S+    6:33PM   0:01.03 puma 4.3.3 (tcp://localhost:3000) [rails-tutorial]
wm               33091   0.0  0.0  4268320    688 s000  S+    6:33PM   0:00.00 grep puma
```
cluster workerが消えた
とりあえず...これでOK?

# 後書き
puma.rbをいじった覚えはないしどのタイミングで書き換わったのかにも心当たりがないし、pumaについての知識もないのでコード3、4がどう違うのかもよくわかっていません。
cluster workerも調べてはみたのですがよく理解できませんでした。

不安要素は多いですがとりあえずこのまま進めてみて、またエラーが発生すれば追記しようと思います。(2020/3/6)

**追記**
puma.rbをいじっていないは嘘でした。
このエラーが起きたのはrailsチュートリアルのプロジェクトなのですが7章リスト7-37でHerokuのWebサーバーをpumaに変更するためにコードを書き加えていました。
この時に書き加えた部分を消すとrails sで正常にサーバーが起動しました。
(2020/3/8)

puma.rbファイルにportを重複して記述していたからでした。

```ruby:/config/puma.rb
port ENV.fetch("PORT") { 3000 } #デフォルトで生成されたもの

port ENV["PORT"] || 3000 #後から書き込んだもの
```
(2020/3/10)


# 参考
[【Rails】portを使っていないのにAddress already in useエラーが出る場合の応急処置](https://qiita.com/aiandrox/items/063833c3c53efc91279c)

# 完全なコード
```zsh:コード1
rails-tutorial % rails s
=> Booting Puma
=> Rails 6.0.2.1 application starting in development
=> Run `rails server --help` for more startup options
[32206] Puma starting in cluster mode...
[32206] * Version 4.3.3 (ruby 2.6.3-p62), codename: Mysterious Traveller
[32206] * Min threads: 5, max threads: 5
[32206] * Environment: development
[32206] * Process workers: 2
[32206] * Preloading application
[32206] * Listening on tcp://127.0.0.1:3000
[32206] * Listening on tcp://[::1]:3000
Exiting
Traceback (most recent call last):
	32: from bin/rails:4:in `<main>'
	31: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/dependencies.rb:325:in `require'
	30: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/dependencies.rb:291:in `load_dependency'
	29: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/dependencies.rb:325:in `block in require'
	28: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.6/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
	27: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.6/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
	26: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.6/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
	25: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.6/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
	24: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.6/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
	23: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/railties-6.0.2.1/lib/rails/commands.rb:18:in `<main>'
	22: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/railties-6.0.2.1/lib/rails/command.rb:46:in `invoke'
	21: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/railties-6.0.2.1/lib/rails/command/base.rb:69:in `perform'
	20: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/thor-1.0.1/lib/thor.rb:392:in `dispatch'
	19: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/thor-1.0.1/lib/thor/invocation.rb:127:in `invoke_command'
	18: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/thor-1.0.1/lib/thor/command.rb:27:in `run'
	17: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/railties-6.0.2.1/lib/rails/commands/server/server_command.rb:138:in `perform'
	16: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/railties-6.0.2.1/lib/rails/commands/server/server_command.rb:138:in `tap'
	15: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/railties-6.0.2.1/lib/rails/commands/server/server_command.rb:147:in `block in perform'
	14: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/railties-6.0.2.1/lib/rails/commands/server/server_command.rb:39:in `start'
	13: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/rack-2.2.2/lib/rack/server.rb:327:in `start'
	12: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/puma-4.3.3/lib/rack/handler/puma.rb:73:in `run'
	11: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/puma-4.3.3/lib/puma/launcher.rb:172:in `run'
	10: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/puma-4.3.3/lib/puma/cluster.rb:413:in `run'
	 9: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/puma-4.3.3/lib/puma/runner.rb:161:in `load_and_bind'
	 8: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/puma-4.3.3/lib/puma/binder.rb:90:in `parse'
	 7: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/puma-4.3.3/lib/puma/binder.rb:90:in `each'
	 6: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/puma-4.3.3/lib/puma/binder.rb:106:in `block in parse'
	 5: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/puma-4.3.3/lib/puma/binder.rb:222:in `add_tcp_listener'
	 4: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/puma-4.3.3/lib/puma/binder.rb:222:in `each'
	 3: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/puma-4.3.3/lib/puma/binder.rb:223:in `block in add_tcp_listener'
	 2: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/puma-4.3.3/lib/puma/binder.rb:229:in `add_tcp_listener'
	 1: from /Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/puma-4.3.3/lib/puma/binder.rb:229:in `new'
/Users/wm/github/rails-tutorial/vendor/bundle/ruby/2.6.0/gems/puma-4.3.3/lib/puma/binder.rb:229:in `initialize': Address already in use - bind(2) for "127.0.0.1" port 3000 (Errno::EADDRINUSE)
```

```ruby:コード2
   def add_tcp_listener(host, port, optimize_for_latency=true, backlog=1024)
      if host == "localhost"
        loopback_addresses.each do |addr|
          add_tcp_listener addr, port, optimize_for_latency, backlog
        end
        return
      end

      host = host[1..-2] if host and host[0..0] == '['
      s = TCPServer.new(host, port)                               #229および283行目
      if optimize_for_latency
        s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
      end
      s.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
      s.listen backlog
      @connected_port = s.addr[1]

      @ios << s
      s
    end
```


```ruby:コード3
# Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers: a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum; this matches the default thread size of Active Record.
#
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

# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
#
port ENV.fetch("PORT") { 3000 }

# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }

# Specifies the `pidfile` that Puma will use.
pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }

# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked web server processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# rails tutorial
workers Integer(ENV["WEB_CONCURRENCY"] || 2)
threads_count = Integer(ENV["RAILS_MAX_THREADS"] || 5)
threads threads_count, threads_count

preload_app!

rackup DefaultRackup
port ENV["PORT"] || 3000
environment ENV["RACK_ENV"] || "development"

on_worker_boot do
  # Worker specific setup for Rails 4.1+
  # See: https://devcenter.heroku.com/articles/
  # deploying-rails-applications-with-the-puma-web-server#on-worker-boot
  ActiveRecord::Base.establish_connection
end

# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory.
#
# preload_app!

# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart
```

```ruby:コード4
# Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum, this matches the default thread size of Active Record.
#
threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i
threads threads_count, threads_count

# Specifies the `port` that Puma will listen on to receive requests, default is 3000.
#
port        ENV.fetch("PORT") { 3000 }

# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }

# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked webserver processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }

# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory. If you use this option
# you need to make sure to reconnect any threads in the `on_worker_boot`
# block.
#
# preload_app!

# The code in the `on_worker_boot` will be called if you are using
# clustered mode by specifying a number of `workers`. After each worker
# process is booted this block will be run, if you are using `preload_app!`
# option you will want to use this block to reconnect to any threads
# or connections that may have been created at application boot, Ruby
# cannot share connections between processes.
#
# on_worker_boot do
#   ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
# end

# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart
```