无法通过Kubernetes入口访问websocket

时间:2018-08-11 01:32:01

标签: spring websocket kubernetes kubernetes-ingress

我已经在GCP的Kubernetes集群上部署了两项服务:

一个是Spring Cloud Api Gateway的实现:

apiVersion: v1
kind: Service
metadata:
  name: api-gateway
spec:
  ports:
  - name: main
    port: 80
    targetPort: 8080
    protocol: TCP
  selector:
    app: api-gateway
    tier: web
  type: NodePort

另一个是后端聊天服务实现,它在/ws/路径下公开WebSocket。

apiVersion: v1
kind: Service
metadata:
 name: chat-api
spec:
  ports:
  - name: main
    port: 80
    targetPort: 8080
    protocol: TCP
  selector:
    app: chat
    tier: web
  type: NodePort

API网关通过Contour Ingress Controller公开给互联网:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: api-gateway-ingress
  annotations:
    kubernetes.io/tls-acme: "true"
    certmanager.k8s.io/cluster-issuer: "letsencrypt-prod"
    ingress.kubernetes.io/force-ssl-redirect: "true"
spec:
  tls:
  - secretName: api-gateway-tls
    hosts:
    - api.mydomain.com.br
  rules:
  - host: api.mydomain.com.br
    http:
      paths:
      - backend:
          serviceName: api-gateway
          servicePort: 80

网关将传入呼叫路由到/chat/上的聊天服务的/ws/路径:

@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
            .route(r -> r.path("/chat/**")
                    .filters(f -> f.rewritePath("/chat/(?<segment>.*)", "/ws/(?<segment>.*)"))
                    .uri("ws://chat-api"))
            .build();
}

当我尝试通过网关连接到WebSocket时,出现403错误:

error: Unexpected server response: 403

我什至尝试使用http,https,ws和wss连接,但错误仍然存​​在。

有人知道吗?

1 个答案:

答案 0 :(得分:3)

在使用Contour 0.5.0的Ingress资源时,我遇到了同样的问题,但是我设法通过 使用IngressRoute将Contour升级到v0.6.0-beta.3(不过请注意,它是beta版)。

您可以像这样添加IngressRoute资源(crd)(删除先前的Ingress资源):

#ingressroute.yaml
apiVersion: contour.heptio.com/v1beta1
kind: IngressRoute
metadata:
  name: api-gateway-ingress
  namespace: default
spec:
  virtualhost:
    fqdn: api.mydomain.com.br
    tls:
      secretName: api-gateway-tls
  routes:
    - match: /
      services:
        - name: api-gateway
          port: 80
    - match: /chat
      enableWebsockets: true # Setting this to true enables websocket for all paths that match /chat
      services:
        - name: api-gateway
          port: 80

然后应用

仅在/chat路径上授权Websocket。

有关{contour IngressRoute}的更多详细信息,请参见here