Skip to content

HOWTO devops Apache2_reverse_proxy_for_containers

steveoro edited this page Mar 30, 2021 · 1 revision

HOWTO: setup a reverse proxy on Apache2 for multiple backend apps or containers

References:

A reverse proxy is a type of proxy server that takes HTTP(S) requests and transparently distributes them to one or more backend servers.

If your Apache server acts as both HTTP and HTTPS server, your reverse proxy configuration must be placed in both the HTTP and HTTPS virtual hosts.

Prerequisites:

  • Ubuntu 18.04
  • A sudo user on the server
  • Apache2 web server
  • site secured with SSL

1. Install the required modules

$> sudo a2enmod proxy
$> sudo a2enmod proxy_http
$> sudo a2enmod proxy_balancer
$> sudo a2enmod lbmethod_byrequests

Restart Apache:

$> sudo systemctl restart apache2

2. Modify the Default Configuration to Enable Reverse Proxy

Assuming the default site is on (000-default.conf), edit the Apache VHost configuration:

$> sudo vi /etc/apache2/sites-enabled/000-default.conf

2.1. Example 1 - Reverse Proxying a Single Backend Server

Example conf. file:

<VirtualHost *:80>
    ProxyPreserveHost On

    ProxyPass / http://127.0.0.1:8080/
    ProxyPassReverse / http://127.0.0.1:8080/
</VirtualHost>
  • ProxyPreserveHost makes Apache pass the original Host header to the backend server.
  • ProxyPass is the main proxy configuration directive. In this case, it specifies that everything under the root URL (/) should be mapped to the backend server at the given address.
  • ProxyPassReverse should have the same configuration as ProxyPass. It tells Apache to modify the response headers from backend server.

Restart Apache afterwards:

$> sudo systemctl restart apache2

2.2 Example 2 - Load Balancing Across Multiple Backend Servers

If you have multiple backend servers, a good way to distribute the traffic across them when proxying is to use load balancing features of mod_proxy.

Example conf. file for 2 backend servers running on localhost @ :8080 & :8081:

<VirtualHost *:80>
<Proxy balancer://mycluster>
    BalancerMember http://127.0.0.1:8080
    BalancerMember http://127.0.0.1:8081
</Proxy>

    ProxyPreserveHost On

    ProxyPass / balancer://mycluster/
    ProxyPassReverse / balancer://mycluster/
</VirtualHost>

This will redistribute the response for each request to port :80 equally between the 2 backends.

Clone this wiki locally