WebSocket is a full-duplex communication protocol built on TCP. It allows persistent connections between clients and servers, enabling real-time, bidirectional data transfer. Compared to traditional HTTP polling, WebSocket is more efficient and has lower latency, making it ideal for scenarios like chat apps, live data streaming, and real-time notifications.
In production environments, Nginx is often used as a reverse proxy for handling load balancing, access control, and routing. To support the WebSocket protocol through Nginx, some additional configuration is needed to ensure stable, persistent connections to the backend service.
First, ensure that Nginx is installed on your server. Use a package manager depending on your operating system:
sudo apt install nginx # Debian/Ubuntu sudo yum install nginx # CentOS
After installation, run nginx -v to verify that Nginx is properly installed.
Next, modify your Nginx configuration file, usually located at /etc/nginx/nginx.conf or in a file under sites-enabled.
map $http_upgrade $connection_upgrade { default upgrade; '' close; } upstream backend { server 127.0.0.1:8080; }
This block maps the Upgrade header to a connection variable and defines the backend server (adjust the address according to your setup).
location /websocket { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; }
This block proxies WebSocket requests to the backend, while preserving the necessary headers to complete the WebSocket handshake successfully.
After saving your changes, restart Nginx using the command:
sudo service nginx restart
This will reload the configuration and enable WebSocket proxying if everything is set correctly.
You can test the WebSocket setup using a browser or any WebSocket client. Below is a simple JavaScript example:
var ws = new WebSocket("ws://your_domain/websocket"); ws.onopen = function() { console.log("Connected to WebSocket"); }; ws.onmessage = function(event) { console.log("Received message: " + event.data); }; ws.onclose = function() { console.log("Disconnected from WebSocket"); };
Embed this script in an HTML file, open it in your browser, and check the console for connection messages.
By configuring Nginx as a WebSocket proxy, you can enable efficient and stable real-time communication in your application. Nginx itself does not handle WebSocket logic; it simply forwards the connection. The actual WebSocket handling must be implemented by your backend service. Combining Nginx with a dedicated WebSocket server is an effective way to build modern real-time applications.