Muitliple Node.js servers using NGINX proxys

2019-03-17 09:49发布

问题:

The Goal:

Use muitiple live node.js servers independent of each other under different doc roots.

Using NGINX

server {
    server_name .lolwut1.com;
    root /var/www/html/lolwut1;
    # proxy pass to nodejs
    location / {
        proxy_pass    http://127.0.0.1:5001/;
    }
}

server {
    server_name .lolwut2.com;
    root /var/www/html/lolwut2;
    # proxy pass to nodejs
    location / {
        proxy_pass    http://127.0.0.1:5002/;
    }
}

/var/www/html/lolwut1/app.js

var http = require('http');
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("lolwut1\n");
});
server.listen(5001);

/var/www/html/lolwut2/app.js

var http = require('http');
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("lolwut2\n");
});
server.listen(5002);

So when I...

node app.js in /var/www/html/lolwut1/app.js and hit lolwut1.com I'm all good.

Questions:

  1. But now what If I want to start the second node server?
  2. Is this a bad approach?... Am I thinking about this the wrong way?
  3. What are the advantages/disadvantages of using node.js with a connect.vhost directive as a router rather than NGINX?

回答1:

  1. Use forever to start and stop your node apps.
  2. You're doing it right! This approach has worked well for me for quite a while.
  3. Connect vhost Advantage: You don't have to install and configure nginx. The whole stack is node.js.

    Nginx Advantage: Nginx is a mature and stable web server. It's very unlikely to crash or exhibit strange behavior. It can also host your static site, PHP site, etc.

    If it were me, unless I needed some particular feature of Nginx, I'd pick Connect vhost or node-http-proxy for the sake of having an all-node.js stack.



回答2:

But now what If I want to start the second node server? Is this a bad approach?...

when you cd to /var/www/html/lolwut2/ and run node app.js, this should start the second server on port 5002 and lolwut2.com should work.

Am I thinking about this the wrong way?

That's a valid way to run multiple node apps on the same server if you have enough memory, and plenty of cpu power. This is also a good way to scale a single node app on the same machine to take advantage of multiple cores by running multiple nodes and using the upstream directive (like here https://serverfault.com/questions/179247/can-nginx-round-robin-to-a-server-list-on-different-ports)



标签: node.js nginx