貼code

2017年2月21日 星期二

用production mode 來部署網站


    一般情況下,直接在專案底下輸入rails server會使用development mode來啟動rails app。但在真正要上線,必須改成使用production mode。這樣一來,你的rails app跑起來才不會出現紅色的error頁面,再來,rails 在production mode會先將一些css js等放在assets裡的東西預先編譯(pre-compile)好來增加網站的效能。要改成production mode,請先完成以下事項。

    首先修改config/secret.yml,設定production mode的secret_key_base。rails 預設已經幫你把develop mode 跟 test mode的給寫好了,但要自己新增production mode中的。原本的secret.yml如下
# Be sure to restart your server when you modify this file.

# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!

# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rails secret` to generate a secure secret key.

# Make sure the secrets in this file are kept private
# if you're sharing your code publicly.

development:
  secret_key_base: aed39a79230a55e79be1e261947e976f66c9830a5b9f438e7b570b3ebbca7b71cbdebbfb7eaef86a06f9a35fc6b3ed257bae12af510dcd23914da0ee32afd157

test:
  secret_key_base: 589c27fe53513bcbcb0a9ec8e6d050fb0661e073e08b8d6220ccbb4eb305e0b73602f6e5fe8b93f08f2fc49a26baf468c1a22dde3a27f6b87f8b761a0fa3dc7e

# Do not keep production secrets in the repository,
# instead read values from the environment.
production:

secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

在終端機底下輸入
rake secret
把生出來的一串東西,取代production: 底下的<%= ENV["SECRET_KEY_BASE"] %>

存擋後,再來在production mode地下的db需要建好。請先把database.yml設定好,看production mode想用哪種sql(通常建議mysql 或 postgresql)
接著在終端機輸入
RAILS_ENV=production bundle exec rake db:migrate

接著要先讓rails 把assets編好,所以一樣在終端機輸入
RAILS_ENV=production bundle exec rake assets:precompile

最後雖然compile了,但production模式預設是不會讓使用者讀取/public/assets的檔案。所以要在config/environments/production.rb裡加上
config.public_file_server.enabled = true

請注意:rails 4以前的版本可能會能夠將config.serve_static_assets = false這行改成true,但在rails 5已經不支援這樣寫了。另外,在網路上有查到
config.assets.serve_static_files = true 這樣的寫法,根據官方文件,這樣寫在rails 5的新一版會被踢除,請改成上面那樣的寫法。

照這樣設定完,就可以在終端機輸入以下來將rails app以production mode跑起來摟!
rails s -e production


參考資料:http://easonchang.logdown.com/posts/2016/08/30/start-your-rails-project-with-production-mode

沒有留言:

張貼留言