jlim8612
By:
jlim8612

Host multiple node.js applications on Digital Ocean using NginX

August 31, 2014 5.3k views

I followed this guide to setup a reverse proxy for my node apps - https://www.digitalocean.com/community/tutorials/how-to-host-multiple-node-js-applications-on-a-single-vps-with-nginx-forever-and-crontab

The gist of it is to include this configuration

server {
    listen 80;

    server_name your-domain.com;

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

This seems to work for the root location - / , but fails when I add a custom folder path. Something like this -

server {
    listen 80;

    server_name your-domain.com;

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

}

My aim is to navigate to my site using example.com/test/ , so that I can list multiple paths for programs. The error I get from chrome is cannot GET example.com/test/

4 Answers

If the node app will be hosted in a subfolder, it can all be done in one server block:

server {
    listen 80;

    server_name your-domain.com;

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

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

}

Note that the port needs to be different for each app.

  • i tried what you posted but it is not working, i have two applications running on 8080 and 8081. The 8081 is in a subfolder of 8080 but they still don't work.

this answer is not for the nginx way. check out [https://github.com/substack/bouncy] or [https://www.npmjs.com/package/bouncy] if you want to do it the Node/Express way.
assume port 8001 is node app A and 8002 is node app B.
change to port 80 and nodemon this file.

var bouncy = require('bouncy');

var server = bouncy(function (req, res, bounce) {
if (req.headers.host === 'beep.example.com') {
bounce(8001);
}
else if (req.headers.host === 'boop.example.com') {
bounce(8002);
}
else {
res.statusCode = 404;
res.end('no such host');
}
});
server.listen(80)

Have another answer? Share your knowledge.