Configure HAProxy LoadBalancer for Apache webserver using Ansible

Girija Varma
3 min readApr 20, 2021
HAProxy

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.

How we can set up the HAProxy?

  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

haproxy.cfg.j2

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

main.yml
main.yml

Here is the small gist of code,

main.yml
output
output

Now from the above two outputs what will you understand that ‘192.168.0.105 ‘is the Load Balancer IP (i.e. frontend) and every time we hit this server new IP will come that are Backend Server ( ‘192.168.0.103’, ‘192.168.0.106’) to this load balancer. so this Ip address 192.168.0.105 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.

Illustration

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 🌞

--

--