Setting up an Apache Reverse Proxy for Docker containers

Setting up an Apache Reverse Proxy for Docker Containers

Using Apache as a reverse proxy for Docker containers is a robust way to manage multiple web services under a single domain. By leveraging Apache’s mod_proxy module, you can route external traffic to internal container ports seamlessly, providing SSL termination and load balancing capabilities.

Prerequisites

  • A Linux server with Docker and Docker Compose installed.
  • Apache HTTP Server installed on the host machine.
  • A registered domain pointing to your server’s public IP.

Step 1: Enabling Required Apache Modules

Before configuring the proxy, you must enable the necessary modules on your Apache installation. Run the following commands to activate proxying, HTTP/2, and header management:

sudo a2enmod proxy

sudo a2enmod proxy_http

sudo a2enmod headers

sudo a2enmod ssl

sudo systemctl restart apache2

Step 2: Configuring the Virtual Host

Create a new configuration file for your service within the Apache sites-available directory. This configuration tells Apache to listen for specific traffic and forward it to the port exposed by your Docker container.

sudo nano /etc/apache2/sites-available/my-app.conf

Add the following configuration block, ensuring you replace the domain name and local port with your specific values:

<VirtualHost *:80>

ServerName myapp.example.com

ProxyPreserveHost On

ProxyPass / http://127.0.0.1:8080/

ProxyPassReverse / http://127.0.0.1:8080/

ErrorLog ${APACHE_LOG_DIR}/myapp-error.log

CustomLog ${APACHE_LOG_DIR}/myapp-access.log combined

</VirtualHost>

Step 3: Deploying the Docker Container

Ensure your Docker container is running and mapped to the port defined in the ProxyPass directive. If your container is defined in a docker-compose.yml file, ensure the port mapping is explicitly set:

services:

web:

image: my-web-app

ports:

- "8080:80"

Step 4: Enabling the Site and Finalizing

Once the configuration is saved, enable the site and restart the Apache service to apply the changes:

sudo a2ensite my-app.conf

sudo systemctl reload apache2

Best Practices for Production

  • SSL/TLS: Always use Certbot (Let’s Encrypt) to generate an SSL certificate for your virtual host to ensure traffic is encrypted.
  • Security: Restrict the ProxyPass directive to specific paths if you are hosting multiple applications on one domain.
  • Logging: Keep the ErrorLog enabled to troubleshoot potential connectivity issues between Apache and the Docker bridge network.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *