Using NGINX to avoid localhost:<arbitrary port>

12 January 2019 - NGINX

You're working on a web project which has a webapp and one or more APIs, perhaps an Identity Server too. Locally, your webapp is http://localhost:5000, your API is http://localhost:5001, your Identity Server is http://localhost:5002, etc, etc.

It's a bit of a pain remembering what port relates to what - especially when this might just be one of many projects you work on.

I'm sure a lot of you already know that you can add local DNS entries with your operating system's hosts file. On Windows this is located at C:\Windows\System32\drivers\etc\hosts, on Mac and Linux, it's /etc/hosts. This file is just a DNS lookup mapping IP addresses to domain names. Your computer will check this file before it tries to find the DNS entry against external DNS servers.

So you could do something like this...

127.0.0.1 web.myapp.local
127.0.0.1 api.myapp.local
127.0.0.1 identity.myapp.local

Unfortunately, the hosts file doesn't support port numbers. So you'd still have to do http://api.myapp.local:5001 - which isn't great as you still have to remember the port number.

A nice way around this is to run NGINX locally and take advantage of its proxy_pass directive. When you first download NGINX, take a look at the nginx.conf file, and add the following server blocks...

server {
    listen       80;
    server_name  web.myapp.local;

    location / {
        proxy_pass       http://localhost:5000;
        proxy_set_header Host $host;
    }
}

server {
    listen       80;
    server_name  api.myapp.local;

    location / {
        proxy_pass       http://localhost:5001;
        proxy_set_header Host $host;
    }
}

Then when you run NGINX, it'll handle your request, and it'll use the request's domain name to determine which app (port number in this case) to pass on the request to.

This means that locally you can now use whatever nice friendly names you like for your different webservices during development, and not have to think about port numbers in your URLs.

If you use Docker, you can even add your NGINX service as part of your docker-compose file, so it's available automatically for all team members when they run docker-compose up (they'll still need to edit their hosts file though).


Please retweet if you enjoyed this post ...

Search


Recent Posts


Featured Posts


.NET Oxford Links