Mapping multiple domains to different nodejs ports using nginx

At the moment of this writing, I only have one VPS, so it wouldn't take long for me to be running more than 1 node app in it.

Since I want to keep all of them working in this semi-production environment (and in a box I have at home). node cannot be using the same port and I don't want to keep stop/restarting an app everytime I'm working on it.

 

Since I've been pretty happy using nginx as a reverse proxy for Apache and a nodejs, then I decided to keep using it and figure how to have multiple nodejs apps running.

 

My scenario, (YMMV):

– I want to have mutiple domains resolving to the same box

– I don't want to change the URL for socket.io

– I know I need to use different ports for different nodejs apps

 

So after googling for a while and discovering that IF is evil. I stumble upon "map" which let me do exactly what I wanted:

Here's the relevant sections of nginx.com (the names have been changed to protect the innocents)

 

http {
.
.
.
    map $http_host $custom_nodejs_port {
        default 50000;
        domain1.com   50000;
        domain2.com   30000;
    }
.
.

server {
        location /socket.io/ {
            rewrite ^/node(.*)$ $1 break;
            proxy_pass http://127.0.0.1:$custom_nodejs_port;

            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";

            proxy_set_header Host $host;
        }
.
.
}

This way I can have multiple nodejs applications running in different ports and nginx will map connections to different domains to them.

The only downside is that I need to reload the config and it's not automatic. Maybe soon…..

 

 

 

Tagged , , , , . Bookmark the permalink.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • IGlr