ActionCableをデプロイ時に使用するために
Railsの非同期通信において使用するActionCableにおいて本番環境で使用する際はまた設定が必要な為、備忘録。
●config/cable.ymlにてadapterの設定
adapterとは
サーバーから送信された情報をクライアントへ提供する仕組みと連携するためのもの
adapterにはいくつか種類がある
・Asyncアダプタ 本番環境での利用は非推奨であるが、個人アプリの規模であれば、基本的に問題はない
・Redisアダプタ 本番環境での利用が推奨されているが、EC2を用いたデプロイを行う際に、幾らか料金がかかる
・ PostgreSQLアダプタ 本番環境での利用が推奨されているが、データベースとのやりとりには、PostgreSQLを使用していることが条件
下記のように記載
config/cable.yml
adapter: async
test:
adapter: test
production:
adapter: async
url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
channel_prefix: mini_talk_app_production
●AWSにてデプロイする際の設定
①本番環境の設定ファイルであるconfig/enviroments/production.rbにて設定
config/enviroments/production.rb
Rails.application.configure do
ActionCable.server.config.disable_request_forgery_protection = true
config.action_cable.url = "ws://【Elastic IP】/cable"
config.action_cable.allowed_request_origins = ['http://【Elastic IP】']
end
上記の箇所にElastic IPと共に記載
②Nginxのrails.confを編集
ターミナル、EC2内にて
sudo vim /etc/nginx/conf.d/rails.conf
server内にて以下を追記
location /cable {
proxy_pass http://app_server/cable;
proxy_http_version 1.1;
proxy_set_header Upgrade websocket;
proxy_set_header Connection Upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
こちらの設定後、Nginxの再起動を行う。
sudo systemctl reload nginx
sudo systemctl restart nginx
この処理後、デプロイで反映実施。