Why Use Node.js for a Reverse Proxy? A Hands‑On Guide
This article explains why Node.js can be a better choice than Nginx for dynamic reverse‑proxy scenarios such as micro‑service gateways, and provides a step‑by‑step tutorial—including installing http‑proxy, creating a mock service, building a proxy server, and testing it.
Why Use Node.js for a Reverse Proxy
When we think of reverse proxies we usually think of Nginx, which is simple to configure and performs well.
So why implement a reverse proxy with Node.js?
A typical use case is a micro‑service gateway.
In a service gateway, the backend consists of many services, each possibly composed of multiple instances; the client only interacts with the gateway, which routes requests to appropriate providers.
The set of available services is dynamic—services may go offline or new ones come online—making Nginx less suitable, whereas a Node.js gateway can adapt more easily.
For example, all services register in ZooKeeper, and Node.js retrieves the list of available services dynamically from ZooKeeper.
Implementation
Node.js’s http‑proxy module makes implementing a reverse proxy straightforward.
(1) Install http‑proxy npm install http-proxy (2) Create a mock backend service (service.js listening on port 8000)
var http = require("http");
http.createServer(function(request, response) {
console.log('request received');
response.writeHead(200, {
"Content-Type": "text/plain"
});
response.write("I'm service A");
response.end();
}).listen(8000);
console.log('service started');(3) Create the reverse proxy server (proxy.js listening on port 8080)
var http = require('http')
var httpProxy = require('http-proxy')
var proxy = httpProxy.createProxyServer();
proxy.on('error', function(err, req, res) {
res.end();
});
var proxy_server = http.createServer(function(req, res) {
proxy.web(req, res, {
target: 'http://localhost:8000'
});
});
proxy_server.listen(8080, function() {
console.log('proxy server is running ');
});(4) Test
Start service.js node service.js Then start proxy.js node proxy.js Visit http://localhost:8080/ in a browser.
You will see the service’s response: I'm service A This demonstrates the basic functionality of a reverse proxy.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
