Here is a guide on installing and configuring HAProxy on an Ubuntu 20.04 machine and securing it using Let’s Encrypt.

Step 1: Update Your System

Open the terminal and enter the following commands to update your system:

sudo apt update
sudo apt upgrade -y

Step 2: Install HAProxy

Install HAProxy by running:

sudo apt install haproxy -y

Step 3: Configure HAProxy

Before configuring, make sure to create a backup of the original configuration:

sudo cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.bak

Next, open the configuration file using. nano (or your preferred text editor):

sudo nano /etc/haproxy/haproxy.cfg

Add the following basic configuration:

frontend http_front
bind *:80
stats uri /haproxy?stats
default_backend http_back
backend http_back
balance roundrobin
server server1 192.168.1.2:80 check
server server2 192.168.1.3:80 check

Please replace 192.168.1.2 and 192.168.1.3 with your servers’ actual IP addresses.

Step 4: Start and Enable HAProxy

To start HAProxy and enable it to start at boot, run:

sudo systemctl start haproxy
sudo systemctl enable haproxy

Step 5: Install Certbot

Certbot is the tool we’ll use to obtain a free SSL certificate from Let’s Encrypt.

Add the repository and install Certbot:

sudo add-apt-repository ppa:certbot/certbotsudo apt update
sudo apt install certbot -y

Step 6: Obtain a Let’s Encrypt SSL Certificate

Now that Certbot is installed use it to request an SSL certificate for your domain:

sudo certbot certonly --standalone --preferred-challenges http -d your-domain.com

Follow the prompts, provide your email address, and agree to the terms of service. Once the certificate is generated, it will be stored in the directory /etc/letsencrypt/live/your-domain.com.

Step 7: Configure HAProxy with SSL

You need to update your HAProxy configuration to use the SSL certificate.

sudo nano /etc/haproxy/haproxy.cfg

Modify the frontend section to look like this:

frontend https_front
bind *:443 ssl crt /etc/letsencrypt/live/your-domain.com/haproxy.pem
reqadd X-Forwarded-Proto:\ https
default_backend http_back

Step 8: Merge Certificate Files

HAProxy requires the full chain and private key to be concatenated into a single file.

sudo bash -c 'cat /etc/letsencrypt/live/your-domain.com/fullchain.pem /etc/letsencrypt/live/your-domain.com/privkey.pem > /etc/letsencrypt/live/your-domain.com/haproxy.pem'

Step 9: Restart HAProxy

Finally, restart HAProxy to apply the changes:

sudo systemctl restart haproxy

Your HAProxy setup should run with an SSL certificate from Let’s Encrypt.

Note: Remember to replace ‘your-domain.com’ with your domain name in all the above commands. Also, the Let’s Encrypt certificates are valid for 90 days.