Search code examples
ubuntunetwork-programmingdnsportforwarding

What is the easiest way on ubuntu to direct a request to a localhost on a different port?


I am setting up a dev environment on an ubuntu virtual box image. I have 2 applications which normally are deployed on different app servers with different ports:

  • App A
    • a.myapp.com:7001
    • web facing app
    • acts like a server to server proxy to services on App B
    • gets the host and port for App B from configuration files
  • App B: b.myapp.com:7002
    • rest services only (not accessible from browser)

On the virtual image I want to just deploy 1 app server with 2 wars to avoid the memory overhead of 2 app servers with 2 separate ports. Long term this would really be like 10 apps so need to keep them all on 1 server.

My current strategy is I am using /etc/hosts to direct any requests bound for a.myapp.com back to localhost and its working well for app A. I would like to do something similar with b.myapp.com:7002 but the port is different and from what I can tell I cant set up the hosts file to change the port.

What is the easiest way in ubuntu to forward a network request bound for b.myapp.com:7002 back to the single app server running on 127.0.0.1:7001. Do I use web proxy like nginx, do I use port forwarding, etc? I'm a bit of a linux noob so be gentle. My main driver is keeping resources minimal. nginx might take a bit more resources but might come in handy for other things long term so open to options.


Solution

  • Turned out to be simple solution using a combination of nginx and hosts file.

    1). Add both domains to /etc/host file

    • 127.0.0.1 a.myapp.com
    • 127.0.0.1 b.myapp.com

    2). install nginx and define one server (reverse proxy) under http section in nginx.config

        server {
            listen 7002;
            #listen 7003; in future I can add N number ports for nginx to listen on
            #listen 7004; in future I can add N number ports for nginx to listen on
            location / {
                proxy_pass http://127.0.0.1:7001/;
            }
        }
    

    The result is:

    • When I go to a.myapp.com:7001 the hosts file forces it to resolve to 127.0.0.1:7001
    • When I go to b.myapp.com:7002 the host file resolves it to 127.0.0.1:7002
      • nginx is listening on 127.0.0.1:7002 and acts as reverse proxy to 127.0.0.1:7001
    • in future I can have same server redirect requests on ports 7003/7004 to port 7001