Dean

Rails 5, ActionCable, Nginx and Puma in Production

I’ve just deployed my first Rails 5 app which had ActionCable built in instead of Pusher.

I couldn’t find any information about running ActionCable in production with Puma using Nginx as the web server.

Here’s a few steps in order to get it working:

First you need to add this in your application layout before the </head> tag

<%= action_cable_meta_tag %>

Next up, in your nginx site config file, copy and update the following:

upstream puma {
  server unix:///tmp/my_app-puma.sock;
  # or server http://127.0.0.1:5000
}

server {
  listen MY_IP:80;
  # server_name example.com;

  root /opt/apps/APP/public;
  access_log /opt/apps/APP/log/nginx.access.log;
  error_log /opt/apps/APP/log/nginx.error.log info;

  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  try_files $uri/index.html $uri @puma;
  location @puma {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    proxy_pass http://puma;
  }

  location /cable {
    proxy_pass http://puma;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";

    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Proto https;
    proxy_redirect off;
  }

  error_page 500 502 503 504 /500.html;
  client_max_body_size 10M;
  keepalive_timeout 10;
}

And lastly, you may need to update your production environment file to change these 2 options:

config.action_cable.url = 'ws://example.com/cable'
config.action_cable.allowed_request_origins = [ 'http://example.com' ]

For SSL, the ws:// above will need to be changed to wss:// and of course, http to https

I hope this helps! :smile:

Copyright 2011-2021 Dean (deanpcmad)

Buy me a Coffee