Skip to main content
Version: 3.9.x

Configure WebSocket Proxying

WebSocket provides persistent, bidirectional communication over a single TCP connection. It is commonly used for live feeds, chat, collaborative applications, and other workloads that exchange data in real time.

API7 Enterprise can proxy the initial HTTP upgrade request and keep the resulting WebSocket connection open. This guide configures a route to a WebSocket upstream and verifies bidirectional traffic through the gateway.

Prerequisites​

Start a Sample WebSocket Server​

Set GATEWAY_CONTAINER to the running API7 Gateway container. Create a dedicated network and connect the gateway to it:

export GATEWAY_CONTAINER=replace-with-gateway-container-name

docker network create gateway-websocket-net
docker network connect gateway-websocket-net "$GATEWAY_CONTAINER"

Start a pinned sample WebSocket server on the shared network:

docker run -d \
--name websocket-server \
--network gateway-websocket-net \
jmalloc/echo-server:v0.3.7

The server exposes a WebSocket endpoint at /.ws that echoes back any message it receives.

For a non-Docker gateway deployment, run the sample server where the gateway can reach it and replace websocket-server in the upstream configuration with that address.

Enable WebSocket on a Route​

WebSocket proxying is enabled on a per-route basis. When enable_websocket is set to true, the Gateway handles the initial HTTP Upgrade handshake and maintains the connection.

Create a Service for the sample upstream and a Route with enable_websocket set to true:

For the Admin API configuration, export the Dashboard token and replace {gateway_group_id} with the target Gateway Group ID. The quickstart Gateway Group uses default.

export API_KEY=replace-with-dashboard-token

Create the Service:

curl -k "https://localhost:7443/apisix/admin/services/websocket-service?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "websocket-service",
"upstream": {
"type": "roundrobin",
"nodes": [
{
"host": "websocket-server",
"port": 8080,
"weight": 1
}
]
}
}'

Create the Route:

curl -k "https://localhost:7443/apisix/admin/routes/websocket-route?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "websocket-route",
"paths": ["/.ws"],
"service_id": "websocket-service",
"enable_websocket": true
}'

Verify the Connection​

Open a connection through API7 Gateway:

websocat "ws://127.0.0.1:9080/.ws"

Send hello. The server should echo the message:

Request served by <container-id>
hello
hello

The open connection and echoed message confirm that the gateway completed the protocol upgrade and proxies traffic in both directions.

Next Steps​

WebSocket traffic can use the same authentication, traffic-management, and observability features applied during the HTTP upgrade request.