Skip to main content

Version: 3.11.0

Proxy WebSocket Connections

WebSocket is a protocol that provides a bidirectional channel between a client and a server over a single TCP connection. It revolutionizes real-time communication on the web where data can be sent and received in real-time. The protocol is widely used in a variety of interactive applications, including chat applications, collaborative editing tools, multiplayer gaming, and more.

This guide will show you how you can use APISIX to proxy WebSocket connections.

Prerequisite(s)

  • Install Docker.
  • Install cURL to send requests to the services for validation.
  • Install websocat to establish WebSocket connections with WebSocket server.
  • Follow the Getting Started tutorial to start a new APISIX instance in Docker.

Start WebSocket Sample Server

Start a sample upstream server with WebSocket support in the same network as the APISIX instance:

docker run -d \
-p 8080:8080 \
--name websocket-server \
--network=apisix-quickstart-net \
jmalloc/echo-server

The server has a WebSocket endpoint at /.ws that echos back any message received.

Create Route in APISIX

Create a route to the sample upstream server and enable WebSocket:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT -d '
{
"id": "ws-route",
"uri": "/.ws",
"enable_websocket": true,
"upstream": {
"type": "roundrobin",
"nodes": {
"websocket-server:8080": 1
}
}
}'

Verify Connections

Establish a connection with the WebSocket server through the route:

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

Send a "hello" message in the terminal, you should see the WebSocket server echoes back the same message:

Request served by 1cd244052136
hello
hello

You can continue to send more messages and the WebSocket server will echo back any message you sent. This shows the bidirectional connection is successful and persistent.

Next Steps

You have now learned how to proxy WebSocket connections with APISIX. If you would like to rate limit to the number of WebSocket connections, see the limit-conn plugin doc for more information (coming soon).


API7.ai Logo

API Management for Modern Architectures with Edge, API Gateway, Kubernetes, and Service Mesh.

Product

API7 Cloud

SOC2 Type IIISO 27001HIPAAGDPRRed Herring

Copyright © APISEVEN Ltd. 2019 – 2024. Apache, Apache APISIX, APISIX, and associated open source project names are trademarks of the

Apache Software Foundation