# Use Caddy as a reverse proxy with custom error pages This guide shows how to run error-pages as a **live sidecar service**, so Caddy can replace 4xx/5xx responses from any upstream with styled error pages - without rebuilding images. > [!NOTE] > Unlike the [Caddy image guide](caddy_image.md), which embeds pre-rendered HTML into a custom Docker image, this > approach runs error-pages as a separate container. The trade-off is slightly more moving parts, but you can update > templates at runtime without touching Caddy at all. We need two files: a `Caddyfile` and a `compose.yml`. The Caddyfile: ```caddy # File: Caddyfile # http:// is required: without an explicit scheme, Caddy defaults to port 443 regardless of the # auto_https setting localtest.me resolves to 127.0.0.1 via public DNS - no /etc/hosts entry needed http://test.localtest.me { # triggers for errors generated by Caddy itself (e.g. upstream unreachable → 502); does NOT # trigger for 4xx/5xx returned by the upstream - those are handled below handle_errors { # rewrite without an extension so error-pages uses the client headers to pick the # response format rewrite * /{err.status_code} reverse_proxy error-pages:8080 } reverse_proxy nginx:80 { @upstream_error status 4xx 5xx handle_response @upstream_error { # rewrite uses {http.reverse_proxy.status_code} as a runtime placeholder; the `error` # directive cannot be used here - it evaluates the status code at config load time and # ignores placeholders, always falling back to 500. # no extension - error-pages negotiates the format via headers from the client request rewrite * /{http.reverse_proxy.status_code} reverse_proxy error-pages:8080 } } } ``` The compose file: ```yaml # yaml-language-server: $schema=https://cdn.jsdelivr.net/gh/compose-spec/compose-spec@master/schema/compose-spec.json # file: compose.yml services: caddy: image: docker.io/library/caddy:2.11-alpine ports: ['80:80/tcp'] volumes: [./Caddyfile:/etc/caddy/Caddyfile:ro] depends_on: # do not start Caddy until error-pages is up and passes its health check, # ensuring the error handler backend is ready before any traffic arrives error-pages: {condition: service_healthy} error-pages: image: ghcr.io/tarampampam/error-pages:4 environment: # choose which built-in HTML template to use for error pages TEMPLATE_NAME: l7 nginx: # any upstream service - replace this with your own application image image: docker.io/library/nginx:1.29-alpine ``` Place both files in the same directory, then run: ```shell docker compose up ``` Now you can verify that everything works as expected: ```shell # nginx serves its default page normally - no error-pages involved curl -s http://test.localtest.me/ | head -n 12 Welcome to nginx!

Welcome to nginx!

``` ```shell # nginx returns 404; Caddy intercepts it and serves a styled error page instead curl -s -H "Accept: text/html" http://test.localtest.me/nonexistent | head -n 15 Not Found