Skip to content

Nginx Ingress Controller x WebSocket

🏷️ TKE Nginx WebSocket

关于在 K8S 中通过 Nginx Ingress Controller 暴露 WebSocket 服务的方法,查到两篇官方文档,说法并不一致。

  1. Miscellaneous #Websockets

    Support for websockets is provided by NGINX out of the box. No special configuration required.

    这里说是不需要额外配置即可以支持 WebSocket。

    另外还建议增加 proxy-read-timeoutproxy-send-timeout 的值。这两个默认都是 60 秒,建议改成大于 3600 秒。

  2. nginxinc / kubernetes-ingress - WebSocket support

    To load balance a WebSocket application with NGINX Ingress controllers, you need to add the nginx.org/websocket-services annotation to your Ingress resource definition. The annotation specifies which services are websocket services. The annotation syntax is as follows:

    yaml
    nginx.org/websocket-services: "service1[,service2,...]"

    这里是说需要添加 nginx.org/websocket-services 注解,另外还提供了一个完整的示例

经过实际的测试,不添加 nginx.org/websocket-services 注解时确实是可以访问 WebSocket 服务的,不过不确定是不是因为版本较新的原因(这里使用的 ingressnginx 组件的版本是 1.1.0)。

这里为了以防万一,三个注解都加了,示例如下:

yaml
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx-controller-jiajia
    nginx.org/websocket-services: "svc-jiajia-websocket"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"
  name: ingress-www-liujiajia-me-websocket
  namespace: jiajia-test
spec:
  rules:
  - host: www.liujiajia.me
    http:
      paths:
      - backend:
          serviceName: svc-jiajia-websocket
          servicePort: 80
        path: /ws/
        pathType: ImplementationSpecific
  tls:
  - hosts:
    - www.liujiajia.me
    secretName: tls-www-liujiajia-me