Production webserver
啟用 SSL 之後,我們要設定應用程式,讓它使用一個適合在 production 環境中使用的 web 伺服器。Heroku 預設使用純 Ruby 實作的 WEBrick,這個伺服器很好設定,不過不適合處理龐大流量。因此 WEBrick 不適合在 production 環境中使用,我們要換成能大量處理請求的 Puma。
WEBrick 設定參考:Ruby Default Web Server
Puma 設定參考:Deploying Rails Applications with the Puma Web Server
按照 Heroku 官方文件,要增加 Puma server 首先要先安裝 puma gem,因為我們只需要在 production 環境中安裝,所以就在 :production group 裡設定:
source 'https://rubygems.org'
.
.
.
group :production do
gem 'pg', '0.17.1'
gem 'rails_12factor', '0.0.2'
gem 'puma', '2.11.1'
end
因為之前有設定執行 bundle 時不要安裝 production 環境中的 gem,不過還是需要更新 Gemfile.lock 檔案:
$ bundle install
下一步就是要建立一個 config/puma.rb 檔案,然後按照 Heroku 文件提供的內容,貼進去:
config/puma.rb
workers Integer(ENV['WEB_CONCURRENCY'] || 2)
threads_count = Integer(ENV['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
最後,我們要在根目錄建立一個 Procfile 檔案,告訴 Heroku 在 production 環境使用 Puma server 處理:
./Procfile
web: bundle exec puma -C config/puma.rb
全部都設定完之後,就可以提交、push、部署:
$ bundle exec rake test
$ git add -A
$ git commit -m "Use SSL and the Puma webserver in production"
$ git push
$ git push heroku
$ heroku run rake db:migrate
現在註冊頁面可以在 production 環境中使用了,注意到網址是 https://,前面還有個鎖頭:
