如何在生产中使用Nginx和Unicorn配置ActionCable?

yza*_*vin 10 nginx unicorn ruby-on-rails-5 actioncable

我最近将我的rails项目从Rails4切换到5.0.0.beta3以使用了令人敬畏的ActionCable.

我的ActionCable服务器在unicorn中运行.在开发中一切正常.在生产中我有

Started GET "/cable" for xxx.xxx.xxx.xxx at 2016-03-28 18:06:38 +0300
Started GET "/cable/" [WebSocket] for xxx.xxx.xxx.xxx at 2016-03-28 18:06
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
Registered connection (189772ff-6229-48f1-ae7f-d9a96ad3a6c3)
Finished "/cable/" [WebSocket] for xxx.xxx.xxx.xxx at 2016-03-28 18:06:35
Run Code Online (Sandbox Code Playgroud)

并且这个消息在循环中一次又一次地重复.

我在stackoverflow上尝试了很多选项来处理这个问题,但没有任何帮助.我的nginx配置:

 upstream unicorn {
   server unix:/tmp/unicorn.my_app.sock fail_timeout=0;
 }

 server {
   server_name www.my_app.com;
   return 301 $scheme://my_app.com$request_uri;
 }

 server {
   listen 80 default deferred;
   server_name my_app.com;
   root /var/www/my_app/current/public;

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

   try_files $uri/index.html $uri @unicorn;
   location @unicorn {
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header Host $http_host;
     proxy_redirect off;
     proxy_pass http://unicorn;
   }

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

   error_page 500 502 503 504 /500.html;
   keepalive_timeout 5;
 }
Run Code Online (Sandbox Code Playgroud)

为了确保允许请求,我暂时在初始化程序中使用此代码: ActionCable.server.config.disable_request_forgery_protection = true

我的cable.coffee档案

 @App ||= {}
 App.cable = ActionCable.createConsumer "/cable"
Run Code Online (Sandbox Code Playgroud)

我的config/cable.yml档案

production:
 adapter: redis
 url: redis://localhost:6379/1
Run Code Online (Sandbox Code Playgroud)

我对这个问题没那么有经验,所以任何帮助都会很棒.

ask*_*kov 6

在该location /cable部分需要添加一行proxy_set_header Host $http_host;

应该:

location /cable {
     proxy_pass http://unicorn/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;
   }
Run Code Online (Sandbox Code Playgroud)


Ric*_*d_G 1

我实施了机架超时。设置正确的超时解决了我的问题。设置这些变量的正确方法是在 config.ru use 语句中,如下所示:

use Rack::Timeout, service_timeout: 5
Run Code Online (Sandbox Code Playgroud)