Reverse Proxy

Run services on multiple local ports on your server and proxy connections from the public internet.
Monday 21st of August 2017 03:26:58 PM

Got some services running on different ports on the same server, or maybe you have a bunch of docker containers mapped to different ports. In my case it was a case of both. Let's say you have a service running on "hostname:8080", if this is a http-based service it would probably be a better idea "funnel" the connection trough a http(s) port 80/443 connection.


This is where "Reverse Proxy" comes into play. The reverse part just means that it is conceptually the opposite of what a "Forward Proxy" (or just proxy) would where a client connects to the internet trough the proxy connection. The Reverse proxy is a layer between your services and the public-IP internet connection on your server. This would work both for multiple servers on different ip-addresses and multiple ports on the same server.

I originally indeed to try nginx as a reverse proxy but I simply refused to listed to any connections...? I gave you a shot nginx, back to good old apache2. Removed nginx and installed apache2 on my Ubuntu 16.04 server.

sudo apt update
sudo apt install apache2

Apache2 is module based, and you would have to install a couple of modules to use reverse proxy. Apache makes it easy to enable modules:

sudo a2enmod proxy
sudo a2enmod proxy_http 

Now all you have to do edit some site config files to setup the proxy routing. Now you have different options for a reverse proxy to the same domain name. Location based or subdomain/virtual host. Location based is just a location on a base uri, like so: "http://domain.com/location", a subdomain would be: "http://subdomain.com". You can also use a combination of both. Apache2 is configured based on sites, sites are added to /etc/apache2/sites/available.

Location
Can be added to any virtual host config or main config file.

ProxyPass "/location" "http://127.0.0.1:8080" connectiontimeout=5 timeout=30
ProxyPassReverse "/location" "http://127.0.0.1:8080"

OR


    	ProxyPass http://localhost:8080
    	ProxyPassReverse http://localhost:8080


Subdomain

	ServerAdmin webmaster@localhost
	ServerName sub.domain.com
	ProxyPass "/" "http://127.0.0.1:8080" connectiontimeout=5 timeout=30
	ProxyPassReverse "/" "http://127.0.0.1:8080"


Enable the site and restart apache for the settings to take effect

sudo a2ensite mysite.conf
sudo apachectl restart


This is only a very basic example, there are many more tweaking possibilites and a lot more info out there. You can also use reverse proxy as a load balancer and apache has a perfect module for that called "proxy_balancer". Check out a guide here. For more reverse proxy info, go to the apache website. Be carful not to leave your apache server as a open proxy, keep "ProxyRequests Off".  More information here.