Back
Tech 2 min read - 4 Apr. 22 - Mayeul Le Monies de Sagazan

Migrating from NGINX to Caddy

In my experience, NGINX configuration quickly becomes complex and can become a part that nobody wants to touch for fear of breaking something. It was this aspect that made me look for an alternative.

Caddy?

First of all, what is Caddy?
It's a cross-platform Web Server written in GO with a simple configuration and automatic HTTPS setup (with Letsencrypt).
Caddy is open source under an Apache 2.0 license. At the time of writing, its Github repository is approaching 40k stars.

Comparison

We're going to compare two minimal configurations to get a basic reverse proxy.

Reverse proxy with NGINX

server {
        listen 443 ssl;
        server_name example.com;

        location / {
                proxy_pass http://localhost:3000;
        }
  
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
}

server {
        listen 80;
        server_name example.com;

        return 301 https://example.com$request_uri;
}
With this configuration, you also need to install certbot and generate the SSL certificate.

Reverse proxy with Caddy

example.com {
        reverse_proxy localhost:3000
}
That's it! Caddy will generate the SSL certificate itself and handle redirecting HTTP requests to HTTPS.

Installation

Convinced by Caddy?
To install it, simply follow the installation instructions here.
Then, create your configuration file: /etc/caddy/Caddyfile
Then, if you have an NGINX server running (or another server listening on ports 80 and 443), you'll need to stop it:
sudo systemctl stop nginx.service
sudo systemctl disable nginx.service
Finally, you'll need to start Caddy and make sure it's launched at every reboot:
sudo systemctl start caddy.service
sudo systemctl enable caddy.service
There you go!
Of course, you can do much more than just simple reverse proxies with Caddy; for example, you can serve static files, perform load balancing, and do gzip compression...
To do all that, you'll unsurprisingly need to read the documentation !

Bonus

Caddy can also be launched without any configuration file, which can be useful for quickly testing something; here are a few examples:

Static file server from the current directory

caddy file-server --listen localhost:4444
It's the equivalent of:
npx serve . -p 4444
but more performant.

Reverse proxy with automatic HTTPS

sudo caddy reverse-proxy --from example.com --to localhost:3000

Do you want support to launch your digital project?

Submit your project now