Rails - ActionCable:"action_cable.url" 用于 Kubernetes/Minikube

Rails - ActionCable: "action_cable.url" for Kubernetes/Minikube

websockets/Rails/Kubernetes/Minukube 和 Nginx 应该配置什么config.action_cable.url

当 运行 “docker-compose” 在本地一个 Nginx 进程在 Rails 进程之前(不只是 API,但是有 SSR)和一个独立的电缆过程(cf the guides),websockets 通过传递以下服务器端(比如“/config/application.rb”,在布局中设置 action_cable_meta_tag 来正常工作):

config.action_cable.url = 'ws://localhost:28080'

我在本地使用 Minikube 定位 Kubernetes:我在 Rails 部署(RAILS_ENV=production)和 Cable 部署之前部署了 Nginx,但我无法让它工作。 Cable 服务是“ClusterIP”类型的内部服务,具有“port”和“targetPort”。我尝试了几种变体。

有什么建议吗?

请注意,我在 Minikube 上使用 Nginx -> Rails + Cable,入口点是 Nginx 服务,我使用的 LoadBalancer 外部类型:

upstream rails {
  server rails-svc:3000;
}
server {
  listen 9000 default_server;
  root /usr/share/nginx/html;
  try_files  $uri @rails;
  add_header  Cache-Control public;
  add_header  Last-Modified "";
  add_header  Etag "";
      

  location @rails {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $http_host;
    proxy_set_header Host $http_host;
    proxy_pass_header   Set-Cookie;
    proxy_redirect off;
    proxy_pass http://rails;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
  }
}

为了允许任何来源,我还设置了:

config.action_cable.disable_request_forgery_protection = true

我有一个答案:在 Minikube 集群中,不要放置任何东西并禁用伪造保护,Rails 将默认为正确的值。当 Nginx 在 Rails pod 和独立的 ActionCable/websocket pod 前面时(Rails 图像是用 bundle exec puma -p 28080 cable/config.ru 启动的),如果我将服务命名为“cable-svc”公开 ActionCable 容器,而“rails-svc”是 Rails 容器的容器,您需要:

  • 在K8中,不要设置CABLE_URI
  • 的配置
  • 在 Rails 后端,您没有 URL(未知 127.0.0.1:some_port),执行:
# config.action_cable.url <-- comment this
config.action_cable.disable_request_forgery_protection=true
  • 在 Nginx 配置中,为“/cable”路径添加特定位置:
upstream rails {
  server rails-svc:3000;
}
server {
  [...root, location @rails {...}]
  location /cable {
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_pass "http://cable-svc:28080";
  }
}

检查日志,Rails 中不再有 WebSockets,Cable 响应。