Search code examples
ruby-on-rails-5pumaactioncable

Action cable not working on production hand shake problem


Action cable is working on development and production mode on local but its not working on production. I am using docker and puma. my puma.rb has following code

#!/usr/bin/env puma

environment ENV.fetch("RAILS_ENV") { "development" }

workers 2
threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i
threads threads_count / 2, threads_count
app_dir = File.expand_path("../..", __FILE__)
daemonize false
preload_app!
bind 'tcp://0.0.0.0:3000'
bind "unix://#{app_dir}/tmp/sockets/puma.sock"
# plugin :tmp_restart
rackup DefaultRackup

tag 'project_puma'

before_fork do
  require 'puma_worker_killer'
  interval = (ENV.fetch("PUMA_WORKER_KILLER_INTERVAL") { 180 }).to_i

  PumaWorkerKiller.enable_rolling_restart(60 * interval)
end

on_worker_boot do
  ActiveSupport.on_load(:active_record) do
    ActiveRecord::Base.establish_connection
  end
end

on_restart do
  ActiveRecord::Base.connection_pool.disconnect!
end

cable.yml

development:
  adapter: redis
  url: redis://localhost:6379/1

test:
  adapter: async

production:
  adapter: redis
  url: <%= ENV.fetch("REDIS_URL") { "redis://redis:6379/1" } %>
  channel_prefix: project_admin_production

and in production.rb I have

config.action_cable.url = "wss://mysite.com/cable"  

in browser console I'm getting Firefox can’t establish a connection to the server at ws://mysite.com/cable. And in logs I can see the error Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: close, HTTP_UPGRADE: ), I'm using rails 5.1.6 and puma 3.4. What I need to do to fix this.


Solution

  • I was able to fix the issue by putting following contents in nginx config

    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-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header Host $http_host;
      break;
    }