How to Run Caddy as a Reverse Proxy on Ubuntu 24.04

by David Park
How to Run Caddy as a Reverse Proxy on Ubuntu 24.04

What You'll End Up With

By the end of this guide you'll have Caddy 2 running as a systemd service on Ubuntu 24.04, terminating TLS automatically via Let's Encrypt, and proxying HTTPS traffic to one or more local backend processes (Node.js, Gunicorn, Go binaries — anything that speaks HTTP). No Certbot cron jobs, no manual certificate renewals, no 800-line nginx config. Total monthly cost: $0 on top of whatever VPS you already run.

Prerequisites

  • Ubuntu 24.04 LTS server (fresh or existing)
  • A non-root user with sudo privileges
  • A domain name with an A record pointing to the server's public IP (DNS must propagate before the TLS step)
  • Port 80 and 443 open in your firewall
  • At least one backend service listening on a local port (e.g., localhost:3000)

1. Install Caddy from the Official Repository

Caddy maintains a Debian/Ubuntu apt repository. Using it ensures you receive signed packages and can upgrade with apt upgrade.

1.1 Install prerequisite packages.

sudo apt update && sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl

1.2 Import the Caddy signing key.

curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' \
  | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg

1.3 Add the repository.

curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' \
  | sudo tee /etc/apt/sources.list.d/caddy-stable.list

1.4 Install Caddy.

sudo apt update && sudo apt install -y caddy

Expected output (last two lines):

Setting up caddy (2.9.1) ...
Created symlink /etc/systemd/system/multi-user.target.wants/caddy.service ...

The package creates the caddy system user, places the binary at /usr/bin/caddy, and registers the caddy.service systemd unit automatically.


2. Understand the Default File Layout

Before editing anything, know where Caddy expects its files.

Path Purpose
/etc/caddy/Caddyfile Main configuration file
/var/lib/caddy/.local/share/caddy TLS certificates and ACME state
/var/log/caddy/ Log output (created on first run)
/usr/bin/caddy Binary

Caddy's systemd unit runs as the caddy user and reads /etc/caddy/Caddyfile on start. You never touch the cert directory manually.


3. Write the Caddyfile

Open the default config.

sudo nano /etc/caddy/Caddyfile

Replace the entire contents with the following. Substitute app.example.com with your real domain and 3000 with your backend port.

# /etc/caddy/Caddyfile

app.example.com {
    reverse_proxy localhost:3000

    log {
        output file /var/log/caddy/app.example.com.log
        format json
    }
}

What each block does:

  • app.example.com {} — Caddy automatically provisions a Let's Encrypt certificate for this hostname on first request.
  • reverse_proxy localhost:3000 — Forwards all requests to your backend. Caddy sets X-Forwarded-For, X-Real-IP, and X-Forwarded-Proto headers by default.
  • log {} — Writes structured JSON access logs to a dedicated file.

Proxying Multiple Apps on One Server

Add additional site blocks in the same file. Each block gets its own certificate.

app.example.com {
    reverse_proxy localhost:3000

    log {
        output file /var/log/caddy/app.example.com.log
        format json
    }
}

api.example.com {
    reverse_proxy localhost:8080

    log {
        output file /var/log/caddy/api.example.com.log
        format json
    }
}

No extra configuration is required for the second certificate. Caddy handles both ACME challenges concurrently.


4. Validate the Caddyfile Before Reloading

Always validate before applying changes. A syntax error in a live Caddyfile causes the reload to fail, but Caddy keeps serving the last known good config — still, catch errors early.

sudo caddy validate --config /etc/caddy/Caddyfile

Expected output:

Valid configuration

If you see an error, it will include the line number and a description. Fix it before proceeding.


5. Enable and Start the Caddy Service

5.1 Enable the service so it starts on boot.

sudo systemctl enable caddy

5.2 Start Caddy (or reload if it's already running).

sudo systemctl restart caddy

5.3 Check the service status.

sudo systemctl status caddy

Expected output (abbreviated):

● caddy.service - Caddy
     Loaded: loaded (/usr/lib/systemd/system/caddy.service; enabled)
     Active: active (running) since Mon 2025-06-02 10:14:03 UTC; 3s ago
       Docs: https://caddyserver.com/docs/
   Main PID: 12345 (caddy)

If Active shows failed, jump to the Troubleshooting section.


6. Apply Config Changes Without Downtime

After any future edit to /etc/caddy/Caddyfile, reload — do not restart. A reload applies the new config with zero dropped connections.

sudo systemctl reload caddy

Alternatively, use Caddy's built-in reload command, which also validates first:

sudo caddy reload --config /etc/caddy/Caddyfile

7. Harden the Setup

These three additions cost nothing and meaningfully reduce your attack surface.

7.1 Add Security Headers

Edit /etc/caddy/Caddyfile and add a header block inside your site block.

app.example.com {
    reverse_proxy localhost:3000

    header {
        Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
        X-Content-Type-Options "nosniff"
        X-Frame-Options "DENY"
        Referrer-Policy "strict-origin-when-cross-origin"
        -Server
    }

    log {
        output file /var/log/caddy/app.example.com.log
        format json
    }
}

The -Server line removes the Server: Caddy response header.

7.2 Rate-Limit the Admin API

Caddy exposes a local admin API on localhost:2019 by default. It is not reachable from outside, but restrict it to loopback explicitly.

Verify the default binding:

ss -tlnp | grep 2019

Expected output:

TCP   LISTEN  0   128   127.0.0.1:2019   0.0.0.0:*

If you see 0.0.0.0:2019, add a global options block at the top of your Caddyfile:

{
    admin localhost:2019
}

app.example.com {
    ...
}

7.3 Configure UFW

If you use UFW, allow only the ports Caddy needs.

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 443/udp

Port 443/udp is required for HTTP/3 (QUIC), which Caddy enables by default.


Verify It Works

Run these checks in order. Each one confirms a different layer of the stack.

Check 1 — TLS certificate issued:

curl -I https://app.example.com

Expected output includes:

HTTP/2 200
strict-transport-security: max-age=31536000; includeSubDomains; preload

Check 2 — Certificate details:

echo | openssl s_client -connect app.example.com:443 -servername app.example.com 2>/dev/null \
  | openssl x509 -noout -issuer -dates

Expected output:

issuer=C=US, O=Let's Encrypt, CN=R11
notBefore=Jun  2 09:14:03 2025 GMT
notAfter=Sep  1 09:14:03 2025 GMT

Check 3 — Backend is receiving proxied requests:

sudo tail -f /var/log/caddy/app.example.com.log | head -5

You should see JSON log lines with "request" objects containing your domain and real client IPs under "remote_ip".

Check 4 — HTTP redirects to HTTPS:

curl -I http://app.example.com

Expected output:

HTTP/1.1 301 Moved Permanently
Location: https://app.example.com/

Caddy adds this redirect automatically for any site block that has a domain name.


Troubleshooting

caddy.service fails to start — port 80 or 443 already in use

Find the conflicting process:

sudo ss -tlnp | grep -E ':80|:443'

Stop it (commonly nginx or apache2):

sudo systemctl stop nginx
sudo systemctl disable nginx

Then restart Caddy.


Certificate not issued — tls: failed to obtain certificate

Caddy logs the reason. Check:

sudo journalctl -u caddy -n 50 --no-pager

Common causes:

  • DNS A record not yet propagated. Verify with dig +short app.example.com.
  • Port 80 blocked by a cloud firewall (AWS Security Group, Hetzner Firewall, etc.) — ACME HTTP-01 challenge requires port 80 to be reachable.
  • Rate-limited by Let's Encrypt (more than 5 duplicate certificates in 7 days). Wait or use a subdomain.

Backend returns 502 Bad Gateway

Confirm the backend is actually running:

curl -s http://localhost:3000

If that fails, the backend process is down — restart it. If it succeeds but Caddy still returns 502, check that the port in your Caddyfile matches exactly.


caddy validate passes but reload fails

Validation checks syntax; some runtime errors (e.g., a port already bound by another Caddy instance) only appear at load time. Check journal:

sudo journalctl -u caddy -n 20 --no-pager

Log file not created

The caddy user must be able to write to /var/log/caddy/. Check ownership:

ls -ld /var/log/caddy/

Expected:

drwxr-x--- 2 caddy caddy 4096 Jun  2 10:14 /var/log/caddy/

If ownership is wrong:

sudo chown -R caddy:caddy /var/log/caddy/

Next Steps

With the Caddy reverse proxy running, the natural next additions are:

  • Wildcard certificates — Use the Caddy DNS plugin for your provider (Cloudflare, Hetzner DNS) and a single *.example.com cert to cover unlimited subdomains without exposing port 80.
  • Basic auth on internal tools — Add basicauth blocks in front of admin panels (Grafana, Flower, pgAdmin) without touching the backend.
  • Metrics — Caddy exports Prometheus metrics at localhost:2019/metrics. Scrape them with a local Prometheus instance and you have request rate, latency, and error tracking at zero additional infrastructure cost.
  • Docker integration — If your backends run in containers, point reverse_proxy at the container's published port or use Caddy's Docker socket integration to auto-discover services from labels.

The Caddyfile format scales cleanly from one app to twenty without the configuration sprawl that comes with nginx sites-available symlinks and manual ssl_certificate directives.