azurenginxvirtual-machinevirtualhostnginx-config

How to host 2 nodejs servers running on different ports(3000 and 5000) using nginx in one virtual machine(azure)


Is it possible to access the 2 nodejs servers like, public_ip:3000 and public_ip:5000? I have an index.js and app.js file in /var/www/html folder. index.js runs on port 3000 and app.js runs on port 5000. I am able to access only the server running on port 3000. If I try to access the other server by public_ip:5000 I am getting a 502 Error.

This is /etc/nginx/site-available/default file config.

server {

    listen 80 default_server;
    listen [::]:80 default_server;
    
    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;

    server_name _;

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

server {

    listen 80;
    listen [::]:80;
    
    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;

    server_name _;

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

Solution

  • There might be a mistake wait let me correct and put the updated code try it once and let me know.

    server {
        listen 80 default_server;
        listen [::]:80 default_server;
    
        root /var/www/html;
        index index.html index.htm index.nginx-debian.html;
    
        server_name _;
    
        location /app1/ {
            proxy_pass http://localhost:3000/;
            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;
        }
    
        location /app2/ {
            proxy_pass http://localhost:5000/;
            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;
        }
    }

    I added path prefixes (/app1/ and /app2/) to the location blocks. http://public_ip/app1/ for the Node.js server running on port 3000 and http://public_ip/app2/ for the one on port 5000. Also added a trailing slash to the proxy_pass URLs.

    sudo service nginx restart

    don't forget to restart NGINX for the changes to take effect.