Configure HAProxy LoadBalancer for Apache webserver using Ansible


HAProxy is a free, open-source platform that provides a high availability load balancer and proxy server for TCP(Layer 4) and HTTP(Layer 7) based applications that request across multiple servers.

With this, we achieve total security i.e isolating the server.

  1. In the inventory file, write all the IP addresses of the managed node, their username, password, and connection type of managed nodes. Here I have grouped my managed node IPs in a group call mywebserver.
inventory file

You can check the connectivity of managed nodes by pinging them

pinging the connectivity

2. Now before running the playbook, in the Controller Node install the haproxy software to get the haproxy.cfg file.

# yum install haproxy -y


Here provide the port number on which you will bind this server. Using the Jinja format with group mywebserver it will automatically add all the IPs from the group to the Inventory file and as this file had Jinja 2 format so we will save it with extension as ‘.j2’ → haproxy.cfg.j2

3. Check the syntax of the playbook, and then run it

# ansible-playbook — syntax-check main.yml

# ansible-playbook -v main.yml


Here is the small gist of code,


Now from the above two outputs what will you understand that ‘ ‘is the Load Balancer IP (i.e. frontend) and every time we hit this server new IP will come that are Backend Server ( ‘’, ‘’) to this load balancer. so this Ip address is serving the client so it called as Proxy Server as it serving on behalf of the main server.

Now with this, we achieved Reverse Proxy as it reverses the proxy to the backend servers, and all client will have to go via this IP 105 to reach to the page, and with this, they give facility of Load Balancing as the first request come they send to IP 103, the second request come they send to IP 106 so on and so forth.


I hope you understood the concept of HAProxy.

⭐️For the complete code use this GitHub repository

For any queries, you can ask me here in the comments.

Thank you 🌞