Link to multiple Node.js apps on single machine without port number

It's common to have multiple Node.js applications running on the same machine. Pointing to each app is easily by different port numbers. For example,

http://localhost:3000  # app1
http://localhost:3001  # app2

How can we make URL more clean? Let's remove port numbers by vhost of Nginx.

Map domain to a service

Assume you have Nginx installed. We want to do following mappings.

  • www.mydomain1.com to service1 on localhost:3000
  • www.mydomain2.com to service2 on localhost:3001

On Ubuntu, we can find configuration settings in this path.
/etc/nginx/sites-available/

For easiness of maintenance, let's add two files for two services.
create file /etc/nginx/sites-available/mydomain1 as

server {
    listen 80;

    server_name http://www.mydomain1.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;
        proxy_set_header X-Forwarded-for $remote_addr;
    }
}

create second file /etc/nginx/sites-available/mydomain2 as

server {
    listen 80;

    server_name http://www.mydomain2.com;

    location / {
        proxy_pass http://localhost:3001;
        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;
        proxy_set_header X-Forwarded-for $remote_addr;
    }
}

Then do the symlink to make our config files effective.

ln -s /etc/nginx/sites-available/mydomain1 /etc/nginx/sites-enabled/mydomain1
ln -s /etc/nginx/sites-available/mydomain2 /etc/nginx/sites-enabled/mydomain2

Then here comes the last step, restart Nginx.
sudo service nginx restart

And that's it!

You might enjoy:

Prev post No more posts

Comments

comments powered by Disqus