Search code examples
node.jsnginxwebproxypass

Hosting multiple node.js instances on nginx


Hey guys I have a Rasberry Pi 4 and I wish to host multiple node.js websites using Nginx, right now I have one instance that runs well and is connected to Cloudflare.

Current 'default' file below

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;

        server_name example.com www.example.com;

        location / {
                proxy_pass http://localhost:5085;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }
}

Now I need to host 2 more websites here, those are - example1.com which runs on localhost:3000 & example2.com which runs on localhost:4000

Now after this, I got another doubt, I need to add these 2 to Cloudflare. Cloudflare DNS for my current website

In image one, I just had to put my public IP Address which was port forwarding at port 80 here's an image for that current port forward setting

Now how would I connect the host to cloudflare. Can someone please help?


Solution

  • You simply have to copy your current nginx server configuration and change the server_name property to server_name example2.com and change the proxy_pass target accordingly.

    It will look like something like this :

    # example.com server/proxy
    server {
       listen 80 default_server;
       listen [::]:80 default_server;
    
       server_name example.com www.example.com;
    
       location / {
           proxy_pass http://localhost:5085;
           # ...
       }
    }
    
    # example2.com server/proxy
    server {
       listen 80;       # we removed the default_server tag here   
       listen [::]:80;  # because it can only be used once  
    
       server_name example2.com www.example2.com;
    
       location / {
           proxy_pass http://localhost:1234;
           # ...
       }
    }