This is a story when I used Action Cable to add a real-time chat function to an application made with Ruby on Rails.
It worked fine in the local environment, but the real-time chat part didn't work in the production environment.
After investigating the cause, it seems that it is necessary to set nginx corresponding to it in order to communicate with websocket used in Action Cable.
This is the original nginx setting. This is also included so that the difference between before and after correction can be easily understood. Before implementing ActionCable, this worked fine.
# https://github.com/puma/puma/blob/master/docs/nginx.md
upstream app {
server unix:///app/tmp/sockets/puma.sock;
}
server {
listen 80;
server_name ***. ***. ***. ***; # IP address of the app
keepalive_timeout 5;
# static files
root /app/public;
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
# static files
if (-f $request_filename) {
break;
}
if (-f $request_filename.html) {
rewrite (.*) $1/index.html break;
}
if (-f $request_filename.html) {
rewrite (.*) $1.html break;
}
if (!-f $request_filename) {
proxy_pass http://app;
break;
}
}
location ~* \.(ico|css|gif|jpe?g|png|js)(\?[0-9]+)?$ {
expires max;
break;
}
}
To be able to handle websocket communication Added location / cable and below.
https://github.com/puma/puma/blob/master/docs/nginx.md
upstream app {
server unix:///app/tmp/sockets/puma.sock;
}
server {
listen 80;
server_name ***. ***. ***. ***; # IP address of the app
keepalive_timeout 5;
# static files
root /app/public;
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
# static files
if (-f $request_filename) {
break;
}
if (-f $request_filename.html) {
rewrite (.*) $1/index.html break;
}
if (-f $request_filename.html) {
rewrite (.*) $1.html break;
}
if (!-f $request_filename) {
proxy_pass http://app;
break;
}
}
# Add the following
location /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;
proxy_set_header Host $http_host;
proxy_pass http://app/cable;
}
#Additional part up to here
location ~* \.(ico|css|gif|jpe?g|png|js)(\?[0-9]+)?$ {
expires max;
break;
}
}
Recommended Posts