LoginSignup
14
15

More than 5 years have passed since last update.

Rails5のActionCableをNginxとPumaの環境にデプロイする

Last updated at Posted at 2017-07-23

はじめに

Rails5のActionCableを使ってリアルタイム通信を本番環境で動かしてみました。
Rails4時代のwebsocker-railsのgemを使ってた頃よりは大分楽にwebsocketを使えるようになってました。

Ruby on Rails5.0.0.rc1のAction Cableを使ってチャットアプリを作ろう!

の記事を参考にさせて頂いて、簡単なチャットアプリを作り本番環境にあげてみました。
本番環境にあげる際に、結構つまずいたところがあったのでメモ。

前提

  • Rails 5.1.2
  • Ruby 2.4.0
  • Puma
  • Nginx
  • Amazon Linux AMI 2017.03.0 (HVM)
    上記の環境がすでに整っており、websocket意外の箇所は正常に動いている。

Nginxの設定で、/cableをwebsocketにあてる

confファイルに、以下を追加して/cablewebsocketにあてます。

/etc/nginx/conf.d/example_cable.conf
location /cable {
        proxy_pass http://[test.com]/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;
    }

ドメインの許可

/config/environments/production.rbファイルを以下のように修正し、ActionCableが受け付けるドメインを指定する。

/config/environments/production.rb
config.action_cable.allowed_request_origins = [ 'http://test.com/', /http:\/\/test.*/ ]

cable.ymlの変更

最初の設定では、redisを使うようになっているのでproductionでasyncに変更します。
そうすると、本番環境でもradisをインストールすることなく動かすことができます。
これに気づかずに、最初はredis突っ込んで動かしてました・・・

/config/cable.yml
production:
  adapter: redis
  url: redis://localhost:6379/1
  channel_prefix: TestActionCable_production

/config/cable.yml
production:
  adapter: async

終わりに

以上が、本番環境でActionCableを動かす方法のメモです。
Railsのバージョンによっても、変更しないといけない箇所変わってくるみたいなのでそこだけはご注意ください。

14
15
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
14
15