TExcelTAD
Home › Kubernetes › TLS with cert-manager

TLS with cert-manager

Every public endpoint needs a TLS certificate, and every certificate expires. Public certificates from Let's Encrypt last 90 days, and the CA/Browser Forum has scheduled public certificate lifetimes to shrink step by step to 47 days by 2029. Renewing by hand stopped being realistic long ago. cert-manager is the CNCF project that turns certificates into Kubernetes objects: you declare which names you need, it obtains the certificate, stores it in a Secret, and renews it before it expires. The Ingress lesson showed the one-line annotation; this lesson shows what happens behind it.

bash
helm install cert-manager oci://quay.io/jetstack/charts/cert-manager \
  --namespace cert-manager --create-namespace --set crds.enabled=true

The building blocks

Resource Scope Purpose
Issuer / ClusterIssuer namespace / cluster Who signs: ACME (Let's Encrypt, ZeroSSL, …), an internal CA, Vault, a self-signed root
Certificate namespace What you want: DNS names, duration, key type, target Secret
CertificateRequest namespace One signing attempt, created by cert-manager for a Certificate
Order / Challenge namespace ACME only: the order with the CA and one challenge per domain
text
Certificate ──► CertificateRequest ──► Order ──► Challenge (one per DNS name)
     │                                   │             │
     │                                   │             └─ HTTP-01: serve a token over :80
     │                                   │                DNS-01: publish a TXT record
     ▼                                   ▼
Secret shop-tls (tls.crt, tls.key, ca.crt)   ◄── finalize: CA signs the CSR

A Let's Encrypt ClusterIssuer with both challenge types:

yaml
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-prod
spec:
  acme:
    server: https://acme-v02.api.letsencrypt.org/directory
    email: platform@example.com
    privateKeySecretRef: {name: letsencrypt-prod-account}
    solvers:
      - selector:
          dnsZones: [example.com]               # anything under example.com: DNS-01
        dns01:
          route53:
            region: eu-west-1
            hostedZoneID: Z0123456789ABCDEF
      - selector:
          dnsNames: [shop.example.org]          # this one name: HTTP-01 through a Gateway
        http01:
          gatewayHTTPRoute:
            parentRefs: [{name: public, namespace: infra, kind: Gateway}]

And a Certificate:

yaml
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: shop
  namespace: shop
spec:
  secretName: shop-tls
  dnsNames: [shop.example.com, "*.shop.example.com"]
  issuerRef: {name: letsencrypt-prod, kind: ClusterIssuer}
  duration: 2160h              # 90 days (what we ask for; Let's Encrypt decides anyway)
  renewBefore: 720h            # renew 30 days before expiry
  privateKey:
    algorithm: ECDSA
    size: 256
    rotationPolicy: Always     # a new key at each renewal (the default since cert-manager 1.18)

Instead of writing Certificates yourself, you can annotate an Ingress (cert-manager.io/cluster-issuer: letsencrypt-prod) or a Gateway; cert-manager's ingress-shim then creates the Certificate from the TLS section's hosts and Secret name.

HTTP-01 or DNS-01?

The CA needs proof that you control each name. With HTTP-01, cert-manager creates a tiny solver Pod plus a route that answers http://<name>/.well-known/acme-challenge/<token>; the CA fetches it over port 80. With DNS-01, cert-manager writes a TXT record _acme-challenge.<name> through your DNS provider's API, waits until it is visible, and the CA queries it.

HTTP-01 DNS-01
Needs Port 80 reachable from the internet, routing to the cluster API credentials for the DNS zone
Wildcards (*.example.com) Not allowed Allowed
Internal-only hosts No (the CA must reach you) Yes
Many clusters behind one name Fragile (the request may land on another cluster) Works
Speed Seconds Waits for DNS propagation

cert-manager picks a solver per DNS name: the solver whose selector matches most specifically wins (dnsNames beats dnsZones, a longer zone beats a shorter one, a selector beats no selector). This model applies those rules and then checks whether the challenge can succeed:

python · try it yourself
SOLVERS = [
    {"name": "route53", "type": "DNS-01", "dnsZones": ["example.com"]},
    {"name": "gateway", "type": "HTTP-01", "dnsNames": ["shop.example.org"]},
    {"name": "internal-dns", "type": "DNS-01", "dnsZones": ["corp.example.com"]},
    {"name": "fallback", "type": "HTTP-01"},
]
PUBLIC_PORT_80 = {"shop.example.org", "blog.example.net"}

def specificity(solver, name):
    base = name.removeprefix("*.")
    if name in solver.get("dnsNames", []):
        return (3, 0)
    zones = [z for z in solver.get("dnsZones", []) if base == z or base.endswith("." + z)]
    if zones:
        return (2, max(len(z) for z in zones))
    if "dnsNames" not in solver and "dnsZones" not in solver:
        return (1, 0)
    return None

def plan(name):
    scored = [(specificity(s, name), s) for s in SOLVERS]
    scored = [(score, s) for score, s in scored if score]
    score, solver = max(scored, key=lambda x: x[0])
    if solver["type"] == "HTTP-01":
        if name.startswith("*."):
            return solver, "FAIL: wildcards need DNS-01"
        if name not in PUBLIC_PORT_80:
            return solver, "FAIL: CA cannot reach port 80"
        return solver, f"GET http://{name}/.well-known/acme-challenge/<token>"
    return solver, f"TXT _acme-challenge.{name.removeprefix('*.')}"

for name in ["shop.example.com", "*.shop.example.com", "vpn.corp.example.com",
             "shop.example.org", "blog.example.net", "*.example.net"]:
    solver, action = plan(name)
    print(f"{name:22} {solver['name']:13} {solver['type']:8} {action}")
shop.example.com       route53       DNS-01   TXT _acme-challenge.shop.example.com
*.shop.example.com     route53       DNS-01   TXT _acme-challenge.shop.example.com
vpn.corp.example.com   internal-dns  DNS-01   TXT _acme-challenge.vpn.corp.example.com
shop.example.org       gateway       HTTP-01  GET http://shop.example.org/.well-known/acme-challenge/<token>
blog.example.net       fallback      HTTP-01  GET http://blog.example.net/.well-known/acme-challenge/<token>
*.example.net          fallback      HTTP-01  FAIL: wildcards need DNS-01

The renewal timeline

A Certificate is renewed when notAfter - renewBefore is reached; without renewBefore cert-manager renews after two-thirds of the lifetime (30 days before expiry for a 90-day certificate). You can also use renewBeforePercentage to express the same thing relative to the duration. If issuance fails (the DNS API is down, a rate limit was hit), cert-manager retries with exponential back-off, starting at about an hour and capped at 32 hours, so you have weeks of slack before the old certificate actually expires. The model plays out a year with one bad renewal:

python · try it yourself
from datetime import datetime, timedelta

LIFETIME = timedelta(days=90)        # chosen by Let's Encrypt
RENEW_BEFORE = timedelta(days=30)    # spec.renewBefore: 720h
OUTAGE = (datetime(2026, 7, 4), datetime(2026, 7, 7))   # DNS provider API down for 3 days

def issue_ok(t):
    return not (OUTAGE[0] <= t < OUTAGE[1])

t = datetime(2026, 1, 5, 9, 0)
not_after = t + LIFETIME
print(f"{t:%Y-%m-%d %H:%M} issued            expires {not_after:%Y-%m-%d}")
while not_after < datetime(2027, 1, 1):
    old_expiry = not_after
    t = old_expiry - RENEW_BEFORE                # renewal time
    delay = timedelta(hours=1)
    failures = 0
    while not issue_ok(t):
        failures += 1
        print(f"{t:%Y-%m-%d %H:%M} attempt failed     retry in {delay.total_seconds() / 3600:.0f}h")
        t += delay
        delay = min(delay * 2, timedelta(hours=32))
    not_after = t + LIFETIME
    left = old_expiry - t
    print(f"{t:%Y-%m-%d %H:%M} renewed           expires {not_after:%Y-%m-%d} "
          f"(old one had {left.days}d {left.seconds // 3600}h left)")
2026-01-05 09:00 issued            expires 2026-04-05
2026-03-06 09:00 renewed           expires 2026-06-04 (old one had 30d 0h left)
2026-05-05 09:00 renewed           expires 2026-08-03 (old one had 30d 0h left)
2026-07-04 09:00 attempt failed     retry in 1h
2026-07-04 10:00 attempt failed     retry in 2h
2026-07-04 12:00 attempt failed     retry in 4h
2026-07-04 16:00 attempt failed     retry in 8h
2026-07-05 00:00 attempt failed     retry in 16h
2026-07-05 16:00 attempt failed     retry in 32h
2026-07-07 00:00 renewed           expires 2026-10-05 (old one had 27d 9h left)
2026-09-05 00:00 renewed           expires 2026-12-04 (old one had 30d 0h left)
2026-11-04 00:00 renewed           expires 2027-02-02 (old one had 30d 0h left)

Normal renewals happen with 30 days to spare. The three-day DNS outage cost less than three days of that buffer (27 days were still left when the renewal succeeded), and the doubling back-off kept cert-manager from hammering the broken API in the meantime. Two alerts are worth having anyway: the certmanager_certificate_expiration_timestamp_seconds metric getting closer than ~14 days, and certmanager_certificate_ready_status{condition="False"}.

Debugging a stuck certificate

Walk down the chain until you find the object with the error (sample output):

text
$ kubectl get certificate,certificaterequest,order,challenge -n shop
NAME                               READY   SECRET     AGE
certificate.cert-manager.io/shop   False   shop-tls   6m

NAME                                      APPROVED   DENIED   READY   ISSUER             AGE
certificaterequest.cert-manager.io/shop-1 True                False   letsencrypt-prod   6m

NAME                                        STATE     AGE
order.acme.cert-manager.io/shop-1-31749602  pending   6m

NAME                                                   STATE     DOMAIN             AGE
challenge.acme.cert-manager.io/shop-1-31749602-90381   pending   shop.example.com   6m

$ kubectl describe challenge shop-1-31749602-90381 -n shop
...
  Reason:      Waiting for DNS-01 challenge propagation: DNS record for "shop.example.com" not yet propagated

Common causes: the DNS credentials lack permission on the zone, a CAA record forbids the CA, port 80 is blocked or redirected to HTTPS before the challenge path, or you burned through Let's Encrypt's production rate limits while testing (use the staging server https://acme-staging-v02.api.letsencrypt.org/directory until things work). The cmctl CLI helps too: cmctl status certificate shop -n shop prints the whole chain, and cmctl renew shop -n shop forces a renewal.

Beyond public certificates

The same machinery issues internal certificates: a CA issuer backed by a root key in a Secret (or Vault, or a cloud private CA) can sign certificates for databases, webhooks and service-to-service mTLS. cert-manager's CA injector copies a CA bundle into caBundle fields of webhook configurations and CRD conversion webhooks, which is how most of the webhooks from Admission Control get their TLS. For mesh workloads, the companion projects istio-csr and csi-driver-spiffe plug cert-manager into service meshes.

Note: The Secret cert-manager writes is an ordinary kubernetes.io/tls Secret. Anything that reads TLS Secrets (Ingress controllers, Gateways, your own Pods via a volume) picks up renewed certificates, although some apps only read files at start-up and need a restart or a reloader.

Learn more: The Gateway API · Secrets · Custom Resources & CRDs

Test yourself

You need a certificate for *.apps.example.com. Which ACME challenge must you use?

  1. HTTP-01
  2. DNS-01
  3. Either one
  4. TLS-ALPN-01 only

A Certificate has a 90-day lifetime and renewBefore: 720h. When does cert-manager start renewing?

  1. On the expiry day
  2. After 30 days
  3. After 60 days (30 days before expiry)
  4. Every day

A Certificate stays READY False. What is the most useful next step?

  1. Delete the cert-manager namespace
  2. Walk down CertificateRequest, Order and Challenge with kubectl describe to find the failing step
  3. Increase the Pod's memory limit
  4. Switch to HTTP/3