Dienstag, 21. Juni 2011

Simple Loadbalancer with NodeJS HTTPS -> HTTP(S) Servers

Here I use NodeJS with a combination of the module node-http-proxy
To loadbalance requests to several server listening to https oder http

When you have installed NPM like this
curl http://npmjs.org/install.sh | sh
then you can install node-http-proxy by:
npm install http-proxy

 Now you can use this file proxy.js:
var fs = require('fs'),
http = require('http'),
https = require('https'),
httpProxy = require('http-proxy');
var options = {
https: {
key: fs.readFileSync('key.pem', 'utf8'),
cert: fs.readFileSync('cert.pem', 'utf8')
}
};
var addresses = [
{
host: '1.2.3.4',
port: 3000
},
{
host: '4.3.2.1',
port: 3001
}
];
// Next line is for HTTP targets
//------------------
var proxy = new httpProxy.HttpProxy();
// When you have https targets (uncomment these and comment the above line for this)
//------------------
//var proxy = new httpProxy.HttpProxy({.
// target: {
// https: true
// }
//});
https.createServer(options.https, function (req, res) {
var target = addresses.shift();
proxy.proxyRequest(req, res, target);
addresses.push(target);
}).listen(443, "1.2.3.4");
view raw proxy.js hosted with ❤ by GitHub

you can start the load-balancer like this:
node proxy.js

Keine Kommentare:

Kommentar veröffentlichen