In this article you are going to learn how to setup request rate limiting in Caddy using a non standard module.
This articles assumes you have a basic understanding of how modules work in Caddy. You can read more about modules here.
If you know nothing about modules, you can still follow the article and get rate limiting working.
Rate Limiting Module #
You are going to use https://github.com/mholt/caddy-ratelimit non-standard module to implement rate limiting.
Building Caddy with Module #
When using non-standard module you have to build Caddy along with the module. I am going to use Docker and build a custom container image that includes the module.
FROM caddy:builder-alpine AS builder RUN xcaddy build \ --with github.com/mholt/caddy-ratelimit FROM caddy:latest COPY --from=builder /usr/bin/caddy /usr/bin/caddy
Dockerfile
docker build -t caddy:custom .
The above uses the builder image caddy:builder-alpine
, builds Caddy using the xcaddy tool and then copies the built binary in a regular caddy:latest
image.
caddy-custom
image contains Caddy along with the rate limiting module.
Writing Caddyfile #
Set up a simple Caddyfile with basic response.
:80 { handle /api* { respond "API 200" } }
Caddyfile
The above returns a simple API 200 response when sending a request to any endpoint starting with /api
.
curl -i localhost:80/api
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Server: Caddy
Date: Sun, 16 Jul 2023 08:11:03 GMT
Content-Length: 7
API 200