nodejs domain based routing
I have server with single IP address. I have 3 nodejs services. Each service 开发者_开发知识库has its own domain. f.e.
- a.company.com,
- b.company.com,
- c.company.com
They written by different people so integration into single application problematic. My aim is to make nodejs routing of different requests to these different services based on hostname mentioned in GET/POST request. I know that I can use NGINX for such kind of routing but I'm sure it will slowdown whole solution. I still plan to keep speed of 2K Req/s. So I prefer to stay in nice Async world of nodejs.
Any advices?
Thanks
If you're using connect, there's the connect.vhost middleware. The repo itself has an example of using connect.vhost for subdomains. The example could be adapted to using different domains just by changing the host names (for example it could be foo.com
and bar.com
like it is on the example in the first link in this post).
If you want your domains in separate processes, I recommend using node-http-proxy. Or, you could use dnode to divide up some work between processes but still have the one process handle all of the HTTP. It's a good idea to move things that are likely to use up lots of memory or crash in separate processes, so they don't bring the whole server down.
I'm using nodejs TCP-proxy to do this. All explanations are in code.
var net = require('net');
// your hosts
var dns = {
'localhost' : 8000,
'b.host' : 3000,
'a.host' : 3001
};
// Create TCP-server
var server = net.createServer( function(soc){ // soc is socket generated by net.Server
// Incoming request processing
soc.on('data', function(data){
// Create new socket
var client = net.Socket();
// Get host from HTTP headers
var re = /[^\n]+(\r\n|\r|\n)host:\w*([^:]+)/i;
var host = data.toString('utf-8').match(re);
if (! dns[host])
{
soc.end('HTTP/1.1 404 Host not found');
return;
}
// Connect to Node.js application
client.connect(dns[host]);
// Pause soc for inner socket connection
soc.pause();
client.on('connect', function()
{
// Write request to your node.js application
client.write(data.toString('utf-8'));
});
client.on('data', function(cdata)
{
// Return socket to live
soc.resume();
// Write client data to browser
soc.write(cdata.toString('utf-8'));
soc.pipe(soc);
soc.end();
});
client.on('end', function(){
client.destroy();
});
});
}
);
server.on('error', function (err){
// Error processing i just pass whole object
console.log(err);
});
server.listen(8088);
console.log('Server is listening %d\n', 8088);
Use nginx or node-http-proxy
http://blog.nodejitsu.com/http-proxy-middlewares http://blog.nodejitsu.com/http-proxy-intro
精彩评论