Reverse Proxy HTTP and WebSocket Server using Nginx

If you heard about the Reverse Proxy the first time it's kind of cool to know. So let's implement the Reverse Proxy today. Let's first get an overview of it. We will start four node server and use the most used library for WebSocket i.e. socket.io. We will use two servers to handle HTTP requests and use other two to handle WebSocket requests. And yes we will also do load balancing between the two servers. Let's first write the node server...

import express from "express";
import { createServer } from "http";
import { Server } from "socket.io";

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, { /* options */ });

const PORT=process.argv[2] || 8080
app.get("/",(req,res)=>{
    return res.send(`<div>Hi what are you doing ${PORT}</div>`)
})


io.on("connection", (socket) => {
    console.log("New Connection");

    socket.on("message",(msg)=>{

        socket.emit("message",`hello from ${PORT}`)
    })


});

httpServer.listen(PORT,()=>{console.log(`listening on port ${PORT}`);});

To run it on a different port just change the argument while running the cmmand.

node server.js 3000

Run it on ports 3000,5000,8000,7000. Let's now install Nginx on your machine. After that write the config file for Nginx


    upstream httpserver{
        server localhost:5000;
        server localhost:3000;
    }

    upstream websocket{
        server localhost:8000;
        server localhost:7000;
    }

    server {
        listen 80;
        location / {
            proxy_pass http://httpserver;
        }

        location /socket.io/ {
            proxy_pass http://websocket;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_set_header Host $host;
        }
    }ee
}
events {}

In HTTP requests we have just Proxy Pass to the backend. But in a Websocket connection, you have to pass the header so the HTTP connection can be upgraded to the WebSocket connection.

Let's first stop the Nginx

sudo nginx -s stop

Now let's add the config file..

sudo nginx -c "/media/omji/New Volume/web development/blog/proxy/ws.cfg"

Here you should change with your file location.

Now if you go to localhost:80/ you will go to server Port 3000 and if you again refresh you will go to port 5000. Nginx will load balance between 3000 and 8000.

Now check the WebSocket connection using Postman. You have to go to ws://localhost and use the socket.io request type in Postman it will automatically add /socket.io at end of request then you have to listen to message emit and send it to the messageemitter. If you know how to use the socket.io library you know. Then you can use it to test that the Nginx is working.

Screenshot_20221120_214808.png

So here it ends. Hope you like it.