mkto mkto - 4 months ago 10
Node.js Question

Nginx reverse proxy doesnt not appear to be working when Node http-server running

I have a server with two two Single Page Application (using a framework) running using node http-server:

website1 running on port 80: IP_ADDRESS:80
website2 running on port 8080: IP_ADDRESS:8080


Currently the workflow is using this two commands to deploy the two sites

pm2 start /usr/bin/http-server -f --name website1 -- -p 80 -d false
pm2 start /usr/bin/http-server -f --name website2 -- -p 8080 -d false


At the end, our sites run on domain like this:

subdomain.mysite.com for website1
subdomain.mysite.com:8080 for website2.


This is not desired, we wanted like this:

subdomain.mysite.com for website1
subdomain2.mysite.com for website2


I tried to install nginx, with the follow reverse proxy configurations:

server {
listen 80;

server_name subdomain2.mysite.com;

location / {
proxy_pass http://127.0.0.1:8080;
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;
}
}


Hoping that now, if I type subdomain2.mysite.com, it will bring me to the website2 on port 8080, but it didn't, it brings me to website1 on port 80 instead. In fact, I cant be sure if this reverse proxy is working at all.

I am sure I configured something wrongly, what could be the problem?

p/s: I also wonder if I am doing it entirely wrong - if I am using nginx for reverse proxy, should I stop using http-server directly?

Answer

Node and Nginx can't both listen on port 80 at the same time. If you want to reverse proxy both you'll need to use a different port for the first Node app and add another virtual host to your nginx file for it.

For example, changing the first app's port to 8000 would look like:

pm2 start /usr/bin/http-server -f --name website1 -- -p 8000 -d false
pm2 start /usr/bin/http-server -f --name website2 -- -p 8080 -d false

With the following Nginx configuration:

server {
    listen 80;

    server_name subdomain2.mysite.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
        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;
    }
}

server {
    listen 80;

    server_name subdomain1.mysite.com;

    location / {
        proxy_pass http://127.0.0.1:8000;
        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;
    }
}

You probably also want to add the proxy_redirect off; flag to each block.