Arnaud Arnaud - 3 months ago 16
Node.js Question

Run several Node instances on a single server

I bought a DigitalOcean droplet that I want to use to host several websites.

All these websites have servers in Node.js. The structure of my droplet is a directory for each website and a file

server.js
in each directory.

When I want to put a website online, I run
node server.js
in the right directory. This creates an instance of the server that runs on the port 80.

At the same time, I have several domains that I bought at GoDaddy: site1.com, site2.com, etc.

My question is: how should I do to run all Node instances simultaneously, while domains redirect to the right server?

A solution where I don't have to create a file that handles all incoming requests to the server would be preferred (unless this is something very generic that I don't have to modify every time I add a new site).

I thought of using different ports for each website, but I don't think it is possible to redirect a domain site1.com:80 to ip_address:another_port.

Answer

The easier way is by far:

  • Use different ports for each nodejs application
  • Set up firewall rules to close ports besides HTTP, HTTPS etc
  • Install NGINX and set it up as a reverse proxy

This way will also enable you to host all of your static files directly with nginx, handle HTTPS, create access logs... and everything that a webserver usually do!

server {
    listen       80;
    server_name  domain1.com;

    location / {
        proxy_set_header    Host $host;
        proxy_set_header    X-Real-IP $remote_addr;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto $scheme;
        proxy_pass          http://localhost:8001;
    }
}

server {
    listen       80;
    server_name  domain2.com;

    location / {
        proxy_set_header    Host $host;
        proxy_set_header    X-Real-IP $remote_addr;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto $scheme;
        proxy_pass          http://localhost:8002;
    }
}