LoginSignup
11
13

More than 3 years have passed since last update.

Action Cable 本番使用時のNginxとCable.ymlの設定

Last updated at Posted at 2020-03-12

はじめに

Action CableはWebSocket通信技術を用い、リアルタイムなチャットなどの機能を実装できる機能です。
AWS本番環境でのNginxとCable.ymlの設定に関して詰まった箇所を共有します。

chat.gif

前提

  • Rails 5.2.3
  • Puma
  • Nginx
  • AWSでデプロイ
  • Https通信

ローカルではWebsocket通信が正常に動いていることが前提です。

Nginxの設定追加

最後の一行ですが、Httpsの場合はこれがないとコンソール内に403エラーになるので注意してください。

proxy_set_header X-Forwarded-Proto https;

/etc/nginx/conf.d/app_name.conf
location /cable {
        proxy_pass http://puma;
        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;
        proxy_set_header X-Forwarded-Proto https;
        }

Cable.ymlの設定

ドキュメントにも記載されている通り、Production環境ではアダプターに"async"を使用するのは非推奨です。
同時に多数のアクセスがあると捌き切れなくなるようです。

8.1.1.1 Async Adapter
The async adapter is intended for development/testing and should not be used in production.

Heroku にも丁寧な解説があります。
本番環境にはRedisまたはPostgreSQL(DBとして使用しているなら)が必要です。
Real-Time Rails: Implementing WebSockets in Rails 5 with Action Cable

Lastly, Action Cable uses Redis as a data store for transient data, syncing content across instances of your application.

1473343848-1462551406-rails-rack.png

私は一度AWSでRedisを契約し、そのエンドポイントURLを下記productionのアダプターに設定していましたが、たまたまPostgreSQLを使用していたのでこれでいけました。
Redisお金かかるのでpostgresでよかった、、、

/config/cable.yml
development:
  adapter: async

test:
  adapter: async

production:
  adapter: postgresql

Production.rb

自分ドメインからのリクエストを許可します。

/config/environments/production.rb

  config.action_cable.url = 'wss://app_name.com/cable'
  config.action_cable.allowed_request_origins = [ 'https://app_name.com', /https:\/\/app_name.*/ ]
  ActionCable.server.config.disable_request_forgery_protection = true

終わりに

特にNginxの設定と、Redisなどアダプターの設定に大変ハマりました、、
ActionCableはRails5から追加された比較的新しい機能のためか、日本語記事ではHttpsやRedisについての言及が少なく、英語記事を参考にしました。
ご参考になれば幸いです。

11
13
0

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
11
13