Proxy WebSocket Connections
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.
APISIX 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 APISIX.
Prerequisite(s)
- Install Docker.
- Install cURL to configure APISIX through the Admin API.
- Install websocat to establish WebSocket connections.
- Follow the Getting Started tutorial to start an APISIX instance in Docker.
Start a WebSocket Upstream
Set GATEWAY_CONTAINER to the running APISIX container. Create a dedicated network and connect the gateway to it:
export GATEWAY_CONTAINER=replace-with-apisix-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 /.ws, which echoes each received message.
Create a Route
Create a route to the WebSocket endpoint and enable WebSocket proxying:
- Admin API
- ADC
curl "http://127.0.0.1:9180/apisix/admin/routes/websocket-proxy" -X PUT \
-d '{
"uri": "/.ws",
"enable_websocket": true,
"upstream": {
"type": "roundrobin",
"nodes": {
"websocket-server:8080": 1
}
}
}'
services:
- name: websocket-proxy
labels:
docs-example: proxy-websocket
routes:
- name: websocket-proxy
uris:
- /.ws
enable_websocket: true
upstream:
type: roundrobin
nodes:
- host: websocket-server
port: 8080
weight: 1
ADC reconciles services as desired state. Preview the changes owned by this example and confirm that the diff contains no unintended updates or deletions:
adc diff -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=proxy-websocket
Synchronize the reviewed service configuration:
adc sync -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=proxy-websocket
Verify the Connection
Open a connection through APISIX:
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 APISIX completed the protocol upgrade and proxies traffic in both directions.
Next Steps
You have configured APISIX to proxy WebSocket connections. To control the number of concurrent connections, see Rate Limit WebSocket Connections.