首页 Microservices Engine Use Cases Cloud-native gateway Route WebSocket traffic with a cloud-native gateway

Route WebSocket traffic with a cloud-native gateway

更新时间: 2026-08-10 13:57:41

WebSocket enables persistent, low-latency, bidirectional communication between clients and servers. When you access a WebSocket service from outside a Kubernetes cluster, an MSE cloud-native gateway receives and forwards requests to the appropriate backend service based on routing rules. This topic describes how to deploy a WebSocket application in a Container Service for Kubernetes (ACK) cluster and route traffic through an MSE cloud-native gateway.

Prerequisites

  • You have created an ACK managed cluster.

  • You have created an MSE cloud-native gateway of the regular instance type (Professional or Standard Edition). Serverless MSE cloud-native gateways do not support the WebSocket protocol.

Step 1: Deploy the WebSocket application

For detailed instructions, see Create a stateless workload by using a Deployment.

This tutorial uses Kubernetes-native service discovery. A Service resource registers the backend with CoreDNS. The sample backend provides multiple WebSocket endpoints. Apply the following YAML configuration in your ACK cluster:

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: sockbin
  name: sockbin-app
  namespace: default
spec:
  progressDeadlineSeconds: 600
  replicas: 2
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: sockbin
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: sockbin
    spec:
      containers:
        - image: therebelrobot/sockbin
          imagePullPolicy: Always
          name: sockbin
          ports:
            - containerPort: 4080
              protocol: TCP
          resources:
            limits:
              cpu: 500m
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: sockbin
  name: sockbin-service
  namespace: default
spec:
  ports:
    - name: http
      port: 4080
      protocol: TCP
      targetPort: 4080
  selector:
    app: sockbin
  sessionAffinity: None
  type: NodePort

Step 2: Route WebSocket traffic

Add the ACK cluster as a service source for the gateway, and then add the Sockbin service.

Cloud-native gateways support the WebSocket protocol by default. The gateway automatically identifies WebSocket requests based on the HTTP Upgrade header, so no additional protocol configuration is required. If your WebSocket service and HTTP APIs share the same IP address and port, you only need to configure path matching rules in the route.

Add a service source

  1. Log on to the MSE console, and select a region in the top navigation bar.

  2. In the left-side navigation pane, choose Cloud-native Gateway > Gateways. On the Gateways page, click the ID of the gateway.

  3. In the left-side navigation pane, click Routes. Then, click the Source tab.

  4. Click Add Source, configure the following parameters, and then click OK.

    Parameter

    Description

    Source Type

    Select Container Service.

    ACK/ACK Serverless Cluster

    Select the cluster where your backend service is deployed.

    Listen to Kubernetes Ingress

    If you enable this option, the MSE cloud-native gateway automatically listens for changes to Ingress resources and applies the domain name and route configurations defined in those resources.

    If you disable this option, the gateway stops listening to Ingress resources, and any previously applied configurations from those resources become invalid.

    Note

    Domain names and routes that you manually configure in the MSE console take precedence over configurations from Ingress resources.

Add a service

  1. Log on to the MSE console, and select a region in the top navigation bar.

  2. In the left-side navigation pane, choose Cloud-native Gateway > Gateways. On the Gateways page, click the ID of the gateway.

  3. In the left-side navigation pane, click Routes. Then, click the Services tab.

  4. Click Create Service, configure the following parameters, and then click OK.

    Parameter

    Description

    Service Sources

    Select Container Service.

    Namespaces

    Select the namespace of the target cluster.

    Services

    Select your service from the list.

Add a Sockbin route

  1. Log on to the MSE console, and select a region in the top navigation bar.

  2. In the left-side navigation pane, choose Cloud-native Gateway > Gateways. On the Gateways page, click the ID of the gateway.

  3. In the left-side navigation pane, click Routes. Then, click the Routes tab.

  4. Click Add Route, configure the following parameters, and then click Save and Advertise.

    Parameter

    Description

    Route Name

    Enter sockbin-route.

    Domain Name

    Select the default domain name *.

    Path

    For the match condition, select Prefix. For the path value, enter /.

    Scenario

    Select Single Service.

    Backend Service

    Select the target Service and Service Port.

Verify the results

Use one of the following methods to verify that the WebSocket service is available.

Method 1: Test with the Sockbin UI

  1. Log on to the MSE console, and select a region in the top navigation bar.

  2. In the left-side navigation pane, choose Cloud-native Gateway > Gateways. On the Gateways page, click the ID of the gateway.

  3. On the Overview page of the gateway, go to the Gateway Ingress tab. Find the public endpoint of the associated Server Load Balancer (SLB) instance and open it in a browser.

    The gateway routes the request to the Sockbin service UI based on the domain name and path in the WebSocket handshake.

    Output:
    CONNECTING to / ...
    CONNECTED to /
    SENT: Hello Sockbin!
    RESPONSE: { "timestamp": "Tue May 31 2022 07:49:41 GMT+0000 (UTC)", "url": "http://sockb.in/", "reqData": "Hello Sockbin!" }

Method 2: Test with a WebSocket client

You can also use a Python WebSocket client. The following example receives a server response with a 1-second delay.

#!/usr/bin/env python
import asyncio
import websockets
async def hello():
    async with websockets.connect("ws://ip_addr/delay/1000") as websocket:
        await websocket.send("Hello Test")
        text = await websocket.recv()
        print(text)
asyncio.run(hello())

Troubleshooting

WebSocket or WSS connection fails

  1. Check the gateway instance type. Serverless gateways do not support the WebSocket protocol. Use a regular instance (Professional or Standard Edition) instead.

  2. Confirm that the backend service is deployed and supports the WebSocket protocol.

  3. Bypass the gateway and test connectivity to the backend service directly.

  4. Check whether the domain name and path configured in the route match the domain name and path in the WebSocket handshake request.

上一篇: Implement active zone-redundancy using an MSE cloud-native gateway 下一篇: Route gRPC services with a Cloud Native Gateway
阿里云首页 微服务引擎 相关技术圈