問題分析
表現形式
websocket鏈接 報錯 200
1 |
Copy WebSocket connection to 'ws://*********' faile Error during WebSocket handshake: Unexpected response code: 200 |
猜測引起原因以及應對方式
-
后端服務某些filter或者interceptor不兼容ws協議
排查后端服務的filter 或者interceptor 代碼
實在不行 將websocket地址給放開限制 -
流量入口沒有兼容ws協議訪問 如nginx未配置ws協議支持
nginx反向代理要配置一些參數 來達到轉發 websocket請求1 2 3 4 5
Copy location /websocket地址 { proxy_pass http://websocket服務; proxy_set_header Upgrade "websocket"; proxy_set_header Connection "Upgrade"; }
解決方案
由於k8s集群入口是通過邊緣路由(ingress)來管理的 會存在如下的坑
- 額外的配置 只能配置在 ingress的 metadata中 這樣在一個ingress中會全部生效
那么這個時候有兩種方案 來解決
1: ingress轉發tcp 內部增加一個nginx 進行分發
略。。。 因為這個方案 為認為是回避了k8s的原則 不使用此方案 理論上 這個方案是很好做的 就是有點違背k8s的玩法
2: 配置一個新的單獨為所有websocket服務服務的ingress
參考文檔: https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#configuration-snippet
新增一個配置如下的ingress 文件名為 websocket-ingress.yaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
Copy apiVersion: extensions/v1beta1 kind: Ingress metadata: name: ingress名稱 namespace: ingress所屬命名空間 annotations: #ingress使用那種軟件 kubernetes.io/ingress.class: nginx #配置websocket 需要的配置 nginx.ingress.kubernetes.io/configuration-snippet: | proxy_set_header Upgrade "websocket"; proxy_set_header Connection "Upgrade"; spec: rules: - host: 識別的域名 http: paths: #代理websocket服務 - path: /websocket地址 backend: serviceName: websocket服務名稱 servicePort: websocket服務端口 |
啟動該ingress
1 |
Copy kubectl apply -f websocket-ingress.yaml |