How to configure HAProxy for HTTP Redirection in Docker Containers

Last Updated on :March 24, 2024

HAProxy, a powerful and flexible load balancer, becomes even more valuable when deployed within Docker containers. In this blog post we’ll explore the step-by-step process of configuring HAProxy for HTTP redirection in a Docker environment.

Why Use HAProxy for HTTP Redirection in Docker?

HAProxy offers a lightweight, high-performance solution for load balancing. Its ability to handle HTTP traffic redirection makes it a versatile tool for managing web applications. Using HAProxy for HTTP redirection in Docker can help you build scalable, resilient, and efficient architectures for your web applications.

Step 1: Pull the HAProxy Docker Image

Start by pulling the official HAProxy Docker image from the Docker Hub. Following command downloads the latest version of the HAProxy image from the Docker Hub.

docker pull haproxy:latest
Step 2: Create a HAProxy Configuration File

Create a configuration file for HAProxy that includes the necessary settings for HTTP redirection. You can use a simple text editor to create the file. Save it as haproxy.cfg. Below is a basic example:

###haproxy-start###
defaults
    mode http
    timeout client 50000
    timeout server 50000
    timeout connect 5000

backend my_backend
    # Redirect requests with "localhost" host to the specified URL
    redirect prefix http://newdomain.in/newpage code 301 if { hdr(host) -i localhost }

frontend stats
    bind *:8080
    # Define an ACL to match requests with the old path
    acl old-path path_reg ^/
    # Route requests matching the ACL to the backend
    use_backend my_backend if old-path
###haproxy-end###

This configuration sets up HAProxy to listen on port 8080 for incoming HTTP requests. Requests with “localhost” in the host header will be redirected to http://newdomain.in/newpage.

Step 3: Run the HAProxy Container

Now that we have our configuration file, it’s time to run the HAProxy container using the following command:

docker run -d -p 80:80 -v /path/to/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg haproxy:latest

Make sure to replace /path/to/haproxy.cfg with the actual path to your HAProxy configuration file.

Step 4: Test the HTTP Redirection

With the HAProxy container running, open your web browser and navigate to the IP address or domain associated with your HAProxy instance. You should observe that HTTP requests are redirected according to the rules specified in the haproxy.cfg file.

You can find the source code for Docker haproxy image in this blog post on GitHub.
https://github.com/rkshpanigrahi/docker-haproxy-web-redirect

You may also like...

Leave a Reply

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