Rails Action Cable + Nginx 生产环境配置

kxu1988 · May 20, 2018 · 1845 hits

项目背景

最近把公司产品升级到了 Rails5.2,Rails 主要用来提供 API 服务,以及后台数据管理;
同时,Rails 跟 Android APP 之间有部分功能需要用到 WebSocket 通信,
WebSocket 方面采用了 Rails5 的 Action Cable。

在生产环境发布项目时候遇到了诸多问题,官网的文档以及网络上的资料都介绍的不是很强,这里把自己的配置过程分享给大家,有遇到同样需求的朋友可以参考。

Nginx 配置

Nginx 版本使用的最新的稳定版:1.14.0
看官网文档介绍,自从 1.3.13 版本之后,Nginx 实现了一种特殊的运行模式:

http://nginx.org/en/docs/http/websocket.html

since version 1.3.13, 
nginx implements special mode of operation that allows setting up a tunnel between a client and proxied server
if the proxied server returned a response with the code 101 (Switching Protocols), 
and the client asked for a protocol switch via the “Upgrade” header in a request.

所以 proxied server 会把头部带有“Upgrade”和“Connection”的转为 Websocket 协议,Nginx 配置文件例子如下:

upstream deploy {
         server unix:///var/www/api.yoursite.com/shared/tmp/sockets/puma.sock;
 }

location /chat {      #注意,在Rails里有相应的配置
    proxy_pass http://deploy;  #这里对应着我上面的Server
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

Rails 配置

在 config/environments/production.rb 里面加入如下两句话

 config.action_cable.url = ['/chat']   
#这里开始我没有加,nginx日志里一直报找不到网址,后来在Rails的日志里发现这个问题
 config.action_cable.disable_request_forgery_protection = true  
No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.