SoFunction
Updated on 2025-03-03

The perfect combination of WebSocket configuration and Nginx (detailed explanation of the process)

Preface

In modern web applications, WebSocket, as a full-duplex communication protocol, provides powerful support for real-time data transmission. To ensure stability and performance of WebSocket in production, using Nginx as a reverse proxy server is a wise choice. This article will show you how to configure WebSocket in Nginx and verify that it works properly.

1. WebSocket configuration in Nginx

1.1 Install Nginx

Before configuring, make sure Nginx is installed on your system. You can install it using the following command:

Ubuntu/Debian:

sudo apt update
sudo apt install nginx

CentOS/RHEL:

sudo yum install nginx

1.2 Basic Nginx configuration

Open the Nginx configuration file (usually located in /etc/nginx/ or /etc/nginx/sites-available/default) and add the following to support WebSocket connections.

server {
    listen 80;
    server_name ;  # Replace with your domain name    location /ws {  # WebSocket path        proxy_pass http://localhost:8080;  # Your WebSocket Server Address        proxy_http_version 1.1;  # Make sure to use HTTP/1.1        proxy_set_header Upgrade $http_upgrade;  # Required configuration        proxy_set_header Connection "Upgrade";  # Required configuration        proxy_set_header Host $host;  # Keep the host header        proxy_set_header X-Real-IP $remote_addr;  # Client Real IP        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  # Forward IP        proxy_set_header X-Forwarded-Proto $scheme;  # Forwarding Protocol    }
    location / {  #Other requests        proxy_pass http://localhost:8080;  # Can be modified according to actual situation    }
}

1.3 Restart Nginx

After the configuration is complete, Nginx needs to be restarted to apply the changes:

sudo systemctl restart nginx
or
nginx - s reload

2. Verify the correctness of WebSocket configuration

There are many ways to ensure that WebSocket works properly, and here are a few simple and effective ways:

2.1 Developer Tools Using Browser

  • Open your web application and use the developer tools of your browser (usually press F12).
  • Switch to the Network tab.
  • Refresh the page and view the WebSocket connection.
  • Find requests starting with ws:// or wss:// and confirm that their status is 101 Switching Protocols. This means that the WebSocket connection has been successfully established.

2.2 Using wscat test tool

wscat is a very practical command line tool that can help you test WebSocket connections. You can install it through npm:

npm install -g wscat

Then connect to the WebSocket server using the following command:

wscat -c ws:///ws

Enter some messages and confirm that they can be sent and received normally. If everything works, the WebSocket configuration is successful.

2.3 Writing simple client code

You can use the following JavaScript code to verify that WebSocket is working properly on the client side:

const ws = new WebSocket('ws:///ws');
 = () => {
    ('Connected to the WebSocket server!');
    ('Hello, server!');  // Send a test message};
 = (event) => {
    ('Received message from server:', );
};
 = () => {
    ('Disconnected from WebSocket server.');
};
 = (error) => {
    ('WebSocket error:', error);
};

3. Frequently Asked Questions and Solutions

3.1 WebSocket connection status is 404 or 403

  • Cause: This error usually indicates that the path to the WebSocket request is incorrect, or that the location block in the Nginx configuration does not correctly match the WebSocket request.
  • Solution:
    • Make sure that the URL of the WebSocket is consistent with the path in the Nginx configuration. For example, if /ws is configured in Nginx, make sure your WebSocket client also uses ws:///ws.
    • Example: If the client uses ws:///socket and the server listens under /ws, it will cause a 404 error.

3.2 The browser console displays "Connection Refused"

  • reason: This situation usually indicates that the WebSocket server is not running on the specified address and port, or that Nginx does not forward the request correctly to the WebSocket server.
  • Solution

Confirm whether the WebSocket server is running and use the following command to check the port:

netstat -tuln | grep 8080

Make sure that the proxy_pass address in the Nginx configuration matches the address of the WebSocket server.

3.3 The received message is empty or the format is incorrect

  • Cause: This may be due to the server failing to properly parse the sent message, or failing to send the message in the expected format.
  • Solution

Check the server code to ensure that messages are received and processed correctly. For example, in a WebSocket server, you can use the following code to ensure that messages are sent in string format:

('message', (message) => {
    const response = ({ message: message });
    (client => (response));
});

Confirm whether the code logic for processing messages is correct on the client side, for example:

 = (event) => {
    const data = ();
    ('Received message:', );
};

3.4 The connection is often disconnected

  • Cause**: It may be due to insufficient resources (such as CPU, memory) on the server, or the timeout setting of Nginx is too low.
  • Solution

Check the server's resource usage to ensure that all WebSocket connections are handled.

Add the values ​​of proxy_read_timeout and proxy_send_timeout in the Nginx configuration, for example:

location /ws {
    proxy_read_timeout 86400;  # 24 hours    proxy_send_timeout 86400;
    ...
}

Monitor the status of the WebSocket connection to see if any client disconnects abnormally.

3.5 Certificate error occurred while using SSL (wss://)

  • reason: The SSL certificate is not configured correctly, or the certificate does not match the requested domain name.
  • Solution

Make sure the SSL certificate and private key are loaded correctly in the Nginx configuration:

server {
    listen 443 ssl;
    server_name ;
    ssl_certificate /path/to/;
    ssl_certificate_key /path/to/;
    ...
}

Use Let’s Encrypt to get a valid SSL certificate and make sure the certificate is consistent with the accessed domain name. This process can be automated using the certbot tool.

3.6 WebSocket connection is disconnected in a load balancing environment

  • reason: If Nginx is configured with load balancing without maintaining the session (Sticky Sessions), it may cause the WebSocket connection to be disconnected when requesting forwarding.
  • Solution

Use ip_hash in an Nginx configuration to ensure that the same client always connects to the same backend server:

upstream websocket {
    ip_hash;
    server backend1:8080;
    server backend2:8080;
}
server {
    location /ws {
        proxy_pass http://websocket;
        ...
    }
}

This is the article about the perfect combination of WebSocket configuration and Nginx (detailed explanation of the process). For more related WebSocket configuration and Nginx content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!