Forward WebSocket traffic with a cloud-native API gateway

更新时间:
复制 MD 格式

The WebSocket protocol enables persistent, low-latency, bidirectional communication between clients and servers. When a WebSocket service runs inside a Kubernetes cluster, a Cloud-native API Gateway can serve as the entry point to receive external requests and forward them to the appropriate backend based on routing rules. This topic describes how to deploy a WebSocket workload to an Container Service for Kubernetes (ACK) cluster and route its traffic through a Cloud-native API Gateway.

Prerequisites

Step 1: Deploy a WebSocket workload

For more information about how to deploy a stateless workload, see Create a stateless workload Deployment.

This example uses a Kubernetes Service resource to register the backend with CoreDNS for service discovery. The sample backend exposes several WebSocket endpoints. Apply the following manifest to 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.

Add a service source

  1. Log on to the API Gateway console.

  2. In the left-side navigation pane, click Cloud-native API Gateway > Instance. In the top navigation bar, select a region.

  3. On the Instance page, click the target instance ID.

  4. In the left-side navigation pane, click Service. Then, click the Source tab.

  5. Click Create Source, set the parameters, and then click OK.

    Parameter

    Description

    Source Type

    Select ACK.

    ACK/ACK Serverless cluster

    Select the cluster where the backend service is deployed.

    Listen to Kubernetes Ingress

    When enabled, Cloud-native API Gateway automatically detects changes to Ingress resources and applies the domain name and route configurations they define.

    When disabled, the gateway stops listening to Ingress resources and removes any configurations previously applied from them.

    Note

    Domain name and route configurations manually set in the console override configurations from Ingress resources.

Add a service

  1. Log on to the API Gateway console.

  2. In the left-side navigation pane, click Cloud-native API Gateway > Instance. In the top navigation bar, select a region.

  3. On the Instance page, click the target instance ID.

  4. In the left-side navigation pane, click Service. Then, click the Services tab.

  5. Click Create Service, set the parameters, and then click OK.

    Parameter

    Description

    Service Source

    Select ACK.

    Namespace

    Select the namespace of the target cluster.

    Services

    Select the service from the list.

Add a route to the Sockbin service

  1. Create an HTTP API. For more information, see Create an HTTP API.

  2. Click the target API and click Create Route in the upper-left corner.

  3. In the Create Route panel, set the parameters and then click Save and Publish.

    Parameter

    Description

    Route Name

    Enter sockbin-route.

    Domain Name

    Select the default domain name, *.

    Path

    Set the match type to Prefix and the path to /.

    Scenario

    Select Single Service.

    Backend Services

    Select the target Service and Service Port.

Verify the results

You can use either of the following methods to verify the WebSocket service.

Method 1: Test with the Sockbin UI

Open the gateway's public address in a browser to access the Sockbin service UI.sockbin服务的界面

Method 2: Test using a WebSocket client

For example, use the following Python client to test a 1-second delayed response. Replace ip_addr with the public IP address of your gateway.

#!/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())