Deploy on demand SSL certificate with Caddy

ยท

2 min read

I was looking for a solution that will provision SSL certificate to domains that point to my load balancer, so I can add "Custom domain setup" block in feature section of my project ๐Ÿ˜Š. I have come across different articles that suggest to try Openresty or Caddy2 to achieve the requirement.

So I gave Caddy a try and I am surprised at how simple it was to configure the reverse_proxy and enable on demand tls.

{
    email me@binodswain.dev
    admin off
}

https:// {
  tls {
    on_demand
  }

  reverse_proxy {
    to http://localhost:3000
  }
}

The above configuration is all that require to provision certificate for domain pointing to the server IP.

Now, you don't want to provision certificates to every domain that point to your load balancer. just provision to those domain that are registered with you. You can have a database table to keep your customer/user domain and query it to check for valid domains.

on_demand_tls global option has options to check whether to provision a certificate of not as well as restrict the rate of provisioning.

  • ask <url> : it sends a get request to the url with hostname in domain=? query parameter. you can query your table with domain value and send response with 200 status code to allow certificate provisioning.
  • interval and burst allows <n> certificate operations within <duration> interval.

Now the Caddyfile looks like this.

{
    email me@binodswain.dev
    admin off
    on_demand_tls {
        ask https://api.example.com/check
        interval 2m
        burst 5
    }
}

https:// {
  tls {
    on_demand
  }

  reverse_proxy {
    to http://localhost:3000
  }
}

To use the custom domain feature, all your tenant/customer has to do is create a CNAME DNS record that points to your load balancer.

let's say a new record was added to DNS records.

site.example.com CNAME 3600 <load balancer IP>

when the site.example.com is searched then request will go to load balancer IP and then Caddy will make a GET query to ask endpoint. Based on the request status code, content from reverse proxy will be displayed or the request will fail.