Setting up SSL Certificates for HAProxy with certbot
4 min read
Here’s how to automatically setup SSL Certificates for HAProxy using certbot and Let’s Encrypt, without having to restart HAProxy.
This article assumes that you have certbot already installed and HAProxy already running.
As we are using HAProxy, we can’t just run
sudo certbot --haproxy like for nginx because certbot doesn’t officially support HAProxy, yet. Instead we have to use the
certonly command and the
--standalone option to run a standalone webserver.
We also want to include the certbot command in a script later on, so we need to supply all further options via the command line. The basic certbot command we will use, looks like this:
If you try to run the command on the machine where HAProxy is running, it will tell you that port 80 is already in use, because that’s the port HAProxy is listening on. To circumvent that, we will have to tell the standalone server to use another port:
We will also have to tell certbot to keep the certificate until it expires and that it should be renewed when we add new domains to it:
With the certbot part out of the way, we can continue with the HAProxy configuration.
For HAProxy, we begin with setting up a minimal SSL configuration for our example frontend:
We will also tell HAProxy to direct all requests to the standalone webserver to the correct port of the standalone webserver.
Our frontend is now done and looks like this:
The letsencrypt backend sets the server to the local certbot standalone server:
Be sure to validate the config with
haproxy -c -f /path/to/your/haproxy.cfg to check for mistakes.
Now we can reload the HAProxy config and try to run the certbot command from above again. It should work, but we aren’t done yet.
Putting it all together
The next step is to create a script that will execute the certbot command and copy the generated certificate to the directory where HAProxy is looking for it.
The script will be called
cert_renew and it will take a list of domains as an argument.
Using it like
cert_renew domain1.org domain2.net will setup one certificate for both domains at
/etc/haproxy/ssl-certs/cert.pem and reload HAProxy.
Setting up the Cronjob
Next, we will save the script at
/usr/local/bin/cert_renew and setup the cronjob, so that it runs twice per day:
With that done, we only have to change the cronjob entry when we add new domains and never have to worry about expiring certificates again.
This post builds on a few other blog posts which have been really helpful. These are:
- This great post by Lee Hutchinson
- Scott Helme’s post and the comments below
- This post by Skarlso, too