25
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails5のActionCable(WebSocket)をPumaとnginxで本番環境で動かす

Last updated at Posted at 2017-02-23

リアルタイムな処理をしたいときにWebSocketをする実装は、Node.jsが多いかと思いますが、結構めんどう・・・
RailsのActionCableを使ったら簡単に実装できて結構良さげ!、いざデプロイして本番環境で動かそうと思うとわりとRails4時代とは同じようにいかずハマったのでメモ。

rails newした状態からスタート

nginxの設定

/etc/nginx/conf.d/default.conf
server {
  listen  80 default_server;

  root /var/rails-server/public;

  location ~* \.(ico|css|gif|jpe?g|png|js|html)(\?[0-9]+)?$ {
    break;
  }

  location / {
    proxy_pass http://0.0.0.0:3000/;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
  }

  location /cable {
    proxy_pass http://0.0.0.0:3000/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;
  }
}

/cableのpathをwebsocketにまわす

ドメインの設定を加える

/config/environments/production.rb
Rails.application.configure do
  ...
  # config.action_cable.mount_path = nil
  # config.action_cable.url = 'wss://example.com/cable'
  config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
  ...
end

config.action_cable.allowed_request_origins に使われるドメインを記述する

routes.rb修正

/config/routes.rb
Rails.application.routes.draw do
  root 'home#index'

  mount ActionCable.server => '/cable'
end

mount ActionCable.server => '/cable' をroutes.rbに加える

おわり

最終的に行き着いたのがこの設定でした。
シンプルにおさまった!

あとはchannelとか設定して
puma実行

$ RAILS_ENV=production bundle exec puma -d

とかやれば、ガンガンWebSocket使えます。

25
31
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
25
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?