I am using the http-proxy npm module for connecting multiple servers to a single port.
I wrote the following code and it's working fine:
var http = require('http');
var httpProxy = require('http-proxy');
// Proxy Address
var proxyAddresses = [
{
host: "localhost",
port: 3001
},
{
host: "localhost",
port: 3002
}
];
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '9090');
app.set('port', port);
//Create a set of proxy servers
var proxyServers = proxyAddresses.map(function (target) {
return new httpProxy.createProxyServer({
target: target
});
});
/**
* Create HTTP server.
*/
var server = http.createServer(function(req, res){
var proxy = proxyServers.shift();
proxy.web(req, res);
proxyServers.push(proxy);
});
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, function(){console.log("server is listening on port " + port);});
server.on('error', onError);
server.on('listening', onListening);
My problem:
If one of my servers (for example port 3002) is not started or has an error, how can I automatically redirect requests to the other available server (i.e. port 3001)?