Skip to main content

proxy

Write Caddyfiles, and the Compose services for Caddy, CrowdSec and Cloudflare Tunnel.

Caddyfile builder

Caddy is a web server that is often run as a reverse proxy. It receives the requests for your domain from the internet, fetches and renews an HTTPS certificate for the domain by itself, and passes each request to your app. Its config file is called a Caddyfile. A Caddyfile can start with a global block in braces, for settings such as the ACME account email, and then has one block per site.

Caddyfile builds a file with one site. Give it the domain and the name and port of the app to forward to; in a Compose stack, the app’s name is its service name. Each method adds a setting and returns a new Caddyfile:

  • email sets the address for the ACME account that requests certificates.
  • acme_dns gets certificates with a DNS-01 challenge through a DNS provider’s API, for when port 80 cannot be reached from outside. The token is read from the environment variable named by token_env.
  • cloudflared serves the site over plain http://, for use behind a Cloudflare Tunnel, which handles HTTPS itself. It also tells Caddy to trust the private addresses the tunnel arrives from and to read the visitor’s address from the Cf-Connecting-Ip header, so logs and client_ip show the visitor instead of the tunnel.
  • crowdsec checks each visitor’s IP address with a CrowdSec agent at api_url and blocks known attackers. The agent’s URL and key go in a global crowdsec block, the site block gets the crowdsec handler, and the global order crowdsec first runs it before every other handler. The plugin registers no place in Caddy’s directive order.
  • rate_limit allows each IP address requests requests per window.
  • max_body caps the size of a request body.
  • encode turns on response compression, which Caddy leaves off by default. Name the encodings to choose them and their order, as in encode('zstd', 'gzip').
  • log turns on access logs. They go to stderr unless you pass output: a file path such as '/var/log/caddy/access.log', or a Caddy log writer such as 'stdout', 'discard' or 'net localhost:9999'. A file output rotates with roll_size (such as '50MiB'), roll_keep (files kept) and roll_keep_for (such as '2160h'); format sets the encoder, such as 'json'.
  • spa serves a single-page app’s static files from static_dir instead of forwarding to the app, and answers any path that is not a file with index.html.
  • upstreams forwards to several copies of the app, one per port in ports, such as one per worker process. The keywords become reverse_proxy options: lb_policy picks how requests are shared, lb_try_duration and lb_try_interval retry a failed request on another copy, and health_uri, health_interval, health_timeout and fail_duration take a copy out of rotation while it fails its health check. With handle=True the proxy sits inside a handle block, which you need when raw blocks use handle with a matcher: Caddy runs only the first handle that matches, so the proxy becomes the fallback.
  • raw adds a block of Caddyfile text as it is, for directives the builder has no method for. Indent its lines after the first with tabs as they should appear.
  • comment adds a # line to the site block, and notes adds comments at the ends of lines. notes takes a dict from the start of a line, such as 'encode', to its comment.

The file ends with a newline, and a blank line separates the global block from the site.

The DNS provider behind acme_dns, and the crowdsec and rate_limit settings, come from Caddy plugins that the official caddy:2 image does not include. The image you run must have them built in. caddy_svc below picks such an image for Cloudflare DNS and for CrowdSec.


source

Caddyfile

def Caddyfile(
    domain, app:str='app', port:int=5001
):

Build a Caddyfile that serves domain and forwards requests to app:port; each method returns a new Caddyfile.

Caddyfile presets

Most sites need only a few of those settings. caddy builds a Caddyfile from keyword arguments, one per option, and returns it; nothing is written until you call .save(). dns is ignored when cloudflared=True, because behind a tunnel Caddy fetches no certificates at all. The token variable defaults to the provider’s name in capitals followed by _API_TOKEN, such as CLOUDFLARE_API_TOKEN.

caddy_api is caddy with settings suited to an API: a limit of 200 requests a minute from each IP address, a 50 MB cap on request bodies, and compression. The examples below print the file each combination writes.


source

caddy_api

def caddy_api(
    domain, app:str='app', port:int=5001, email:NoneType=None, dns:NoneType=None, dns_token_env:NoneType=None,
    cloudflared:bool=False, crowdsec:bool=False, crowdsec_url:str='http://crowdsec:8080', max_body:str='50m',
    rate:str='200', rate_window:str='1m'
)->str:

Build a caddy Caddyfile for an API, adding a per-IP rate limit, a cap on request bodies and compression.


source

caddy

def caddy(
    domain, # domain to serve, such as example.com or app.example.com
    app:str='app', # name of the app to forward to; in Compose, its service name
    port:int=5001, # port the app listens on
    email:NoneType=None, # ACME account email, so Let's Encrypt can write to you about certificates
    dns:NoneType=None, # DNS provider for a DNS-01 challenge, such as 'cloudflare' or 'duckdns', for when port 80 is not reachable
    dns_token_env:NoneType=None, # environment variable holding the DNS provider's API token; defaults to {DNS}_API_TOKEN, such as CLOUDFLARE_API_TOKEN
    crowdsec:bool=False, # check visitors against a CrowdSec agent; needs a Caddy image with the CrowdSec plugin and a separate crowdsec service
    crowdsec_url:str='http://crowdsec:8080', # URL of the CrowdSec agent; the default is a service called crowdsec on the same Compose network
    cloudflared:bool=False, # serve plain http:// behind a Cloudflare Tunnel; Caddy then fetches no certificates and dns is ignored
    encode:bool=False, # turn on response compression, which Caddy leaves off by default
    access_log:bool=False, # log every request to stderr; Caddy writes no access log by default
)->__main__.Caddyfile:

Build a Caddyfile that forwards domain to app:port, with optional ACME email, DNS-01 challenge, CrowdSec, tunnel mode, compression and access log.

cf = str(caddy('myapp.example.com', port=5001))
assert 'myapp.example.com {' in cf
assert 'reverse_proxy app:5001' in cf
assert cf.count('{') == 1
print(cf)
myapp.example.com {
    reverse_proxy app:5001
}
cf = str(caddy('myapp.example.com', port=5001, dns='cloudflare', email='me@example.com'))
assert 'email me@example.com' in cf
assert 'acme_dns cloudflare {$CLOUDFLARE_API_TOKEN}' in cf
print(cf)
{
    email me@example.com
}
myapp.example.com {
    tls {
        acme_dns cloudflare {$CLOUDFLARE_API_TOKEN}
    }
    reverse_proxy app:5001
}
cf = str(caddy('myapp.example.com', port=5001, crowdsec=True))
assert 'api_url http://crowdsec:8080' in cf
assert 'crowdsec' in cf
assert 'api_key {$CROWDSEC_API_KEY}' in cf
g, site = cf.split('\n\n', 1)   # the plugin's settings are a global option and its handler needs a place in the directive order
assert g == '{\n\torder crowdsec first\n\tcrowdsec {\n\t\tapi_url http://crowdsec:8080\n\t\tapi_key {$CROWDSEC_API_KEY}\n\t}\n}', g
assert '\tcrowdsec\n' in site and 'api_url' not in site
assert str(caddy('a.com', email='a@b.c', crowdsec=True)).startswith('{\n\temail a@b.c\n\torder crowdsec first\n')
print(cf)
myapp.example.com {
    crowdsec {
        api_url http://crowdsec:8080
        api_key {$CROWDSEC_API_KEY}
    }
    reverse_proxy app:5001
}
cf = str(caddy('myapp.example.com', port=5001, cloudflared=True))
assert cf.startswith('{\n\tservers {\n\t\ttrusted_proxies static private_ranges\n\t\tclient_ip_headers Cf-Connecting-Ip\n\t}\n}\n\nhttp://myapp.example.com {')
assert 'reverse_proxy app:5001' in cf
print(cf)
http://myapp.example.com {
    reverse_proxy app:5001
}
from fastcore.test import test_fail, test_eq
cf = str(caddy_api('myapp.example.com'))
assert 'rate_limit' in cf and 'max_size 50m' in cf and 'encode' in cf
assert 'reverse_proxy app:5001' in cf
print('caddy_api() OK')

cf = str(caddy_api('myapp.example.com', crowdsec=True, max_body='100m', rate='50', rate_window='30s'))
assert 'crowdsec' in cf and 'events 50' in cf and 'window 30s' in cf and 'max_size 100m' in cf
print('caddy_api() with crowdsec OK')

cf = str(Caddyfile('myapp.example.com').spa())
assert 'try_files {path} /index.html' in cf and 'file_server' in cf
assert 'reverse_proxy' not in cf
print('spa() OK')

cf = str(caddy('myapp.example.com', encode=True, access_log=True))
assert '\tencode' in cf and '\tlog' in cf
print('encode() and log() OK')

cf = str(Caddyfile('myapp.example.com').log(output='/var/log/caddy/access.log'))
assert '\t\toutput file /var/log/caddy/access.log\n' in cf
for o in ('stdout', 'discard', 'file /tmp/a.log', 'net localhost:9999'): assert f'\t\toutput {o}\n' in str(Caddyfile('a.com').log(o))
assert str(Caddyfile('a.com').log()).splitlines()[1] == '\tlog'
cf = str(Caddyfile('a.com').log('/data/logs/access.log', roll_size='50MiB', roll_keep=20, roll_keep_for='2160h', format='json'))
assert '\tlog {\n\t\toutput file /data/logs/access.log {\n\t\t\troll_size 50MiB\n\t\t\troll_keep 20\n\t\t\troll_keep_for 2160h\n\t\t}\n\t\tformat json\n\t}' in cf
for k,v in dict(roll_size='50MiB', roll_keep=20, roll_keep_for='2160h').items():
    cf = str(Caddyfile('a.com').log('/l.log', **{k: v}))
    assert f'\t\toutput file /l.log {{\n\t\t\t{k} {v}\n\t\t}}\n\t}}' in cf
assert '\tlog {\n\t\tformat json\n\t}' in str(Caddyfile('a.com').log(format='json'))
test_fail(lambda: Caddyfile('a.com').log('stdout', roll_keep=5), contains='file output')
print('log(output=...) OK')
caddy_api() OK
caddy_api() with crowdsec OK
spa() OK
encode() and log() OK
log(output=...) OK
cf = (Caddyfile('ex.com', port=5001).cloudflared().comment('three workers').log('/data/access.log', roll_keep=5, format='json')
      .encode('zstd', 'gzip').raw('@hashed path /js/*\n\thandle @hashed {\n\t\tfile_server\n\t}')
      .upstreams(range(5001, 5003), handle=True, lb_policy='round_robin', health_uri='/health')
      .notes({'trusted_proxies': 'the tunnel', 'client_ip_headers': 'the reader', 'encode': 'smaller pages', 'roll_keep': 'five files'}))
test_eq(str(cf), """{
    servers {
        trusted_proxies static private_ranges   # the tunnel
        client_ip_headers Cf-Connecting-Ip      # the reader
    }
}

http://ex.com {
    # three workers
    log {
        output file /data/access.log {
            roll_keep 5   # five files
        }
        format json
    }
    encode zstd gzip   # smaller pages
    @hashed path /js/*
    handle @hashed {
        file_server
    }
    handle {
        reverse_proxy app:5001 app:5002 {
            lb_policy round_robin
            health_uri /health
        }
    }
}
""")
test_eq(str(Caddyfile('a.com').upstreams([5001, 5002])), 'a.com {\n\treverse_proxy app:5001 app:5002\n}\n')
test_eq(str(Caddyfile('a.com').encode()), 'a.com {\n\tencode\n\treverse_proxy app:5001\n}\n')
print('upstreams, raw, comment and notes OK')

Services

These functions return the settings for one Compose service, as a dict to pass to Compose.svc with **. Every service joins a network called web and restarts unless you stop it, so declare .network('web') in the stack.

caddy_svc writes the Caddyfile from caddy to conf and returns the Caddy service. The service mounts that Caddyfile, keeps certificates and state in the caddy_data and caddy_config volumes, starts after the app service, and publishes ports 80 and 443 unless cloudflared=True. It also picks an image that has the plugins your options need:

options image
none, or only cloudflared=True caddy:2
crowdsec=True serfriz/caddy-crowdsec:latest
dns='cloudflare' serfriz/caddy-cloudflare:latest
dns='cloudflare' and crowdsec=True ghcr.io/buildplan/csdp-caddy:latest

For any other DNS provider, pass an image with that provider’s plugin as image, as the duckdns test below does. The service passes the DNS token and CROWDSEC_API_KEY through from the host’s environment. An absolute conf is mounted from that path. A relative one is mounted as ./ plus its file name, so in that case save the Compose file in the same folder as the Caddyfile. mount sets the mounted path yourself, such as ./Caddyfile for an absolute conf beside the Compose file. Pass your own Caddyfile as caddyfile to write it instead of the one built from the options, or save=False to write nothing.


source

caddy_svc

def caddy_svc(
    domain, app:str='app', port:int=5001, *, dns:NoneType=None, email:NoneType=None, crowdsec:bool=False,
    cloudflared:bool=False, conf:str='Caddyfile', caddyfile:NoneType=None, save:bool=True, mount:NoneType=None, **kw
):

Write the Caddyfile to conf and return a Caddy service for Compose.svc, with an image that has the plugins the options need.

import os, time, tempfile, subprocess
from fastcore.all import urlread, Path
with tempfile.TemporaryDirectory() as tmp:
    kw = caddy_svc('ex.com', conf=f'{tmp}/Caddyfile')
    assert kw['image'] == 'caddy:2'
    assert kw['ports'] == ['80:80', '443:443', '443:443/udp']
    assert kw['depends_on'] == ['app']
    print('caddy_svc() basic OK')

with tempfile.TemporaryDirectory() as tmp:
    kw = caddy_svc('ex.com', cloudflared=True, conf=f'{tmp}/Caddyfile')
    assert 'ports' not in kw
    assert kw['image'] == 'caddy:2'
    assert '\nhttp://ex.com {' in Path(f'{tmp}/Caddyfile').read_text()
    print('caddy_svc() cloudflared OK')

with tempfile.TemporaryDirectory() as tmp:
    kw = caddy_svc('ex.com', crowdsec=True, conf=f'{tmp}/Caddyfile')
    assert kw['image'] == 'serfriz/caddy-crowdsec:latest'
    assert 'CROWDSEC_API_KEY=${CROWDSEC_API_KEY}' in kw['environment']
    print('caddy_svc() crowdsec OK')

with tempfile.TemporaryDirectory() as tmp:
    kw = caddy_svc('ex.com', crowdsec=True, cloudflared=True, conf=f'{tmp}/Caddyfile')
    assert kw['image'] == 'serfriz/caddy-crowdsec:latest'
    assert 'ports' not in kw
    print('caddy_svc() crowdsec+cloudflared OK')

with tempfile.TemporaryDirectory() as tmp:
    kw = caddy_svc('ex.com', dns='cloudflare', conf=f'{tmp}/Caddyfile')
    assert kw['image'] == 'serfriz/caddy-cloudflare:latest'
    assert 'CLOUDFLARE_API_TOKEN=${CLOUDFLARE_API_TOKEN}' in kw['environment']
    print('caddy_svc() cloudflare-dns OK')

with tempfile.TemporaryDirectory() as tmp:
    kw = caddy_svc('ex.com', dns='cloudflare', crowdsec=True, conf=f'{tmp}/Caddyfile')
    assert kw['image'] == 'ghcr.io/buildplan/csdp-caddy:latest'
    assert 'CLOUDFLARE_API_TOKEN=${CLOUDFLARE_API_TOKEN}' in kw['environment']
    assert 'CROWDSEC_API_KEY=${CROWDSEC_API_KEY}' in kw['environment']
    print('caddy_svc() cloudflare-dns+crowdsec OK')

with tempfile.TemporaryDirectory() as tmp:
    kw = caddy_svc('ex.duckdns.org', dns='duckdns', conf=f'{tmp}/Caddyfile', image='serfriz/caddy-duckdns:latest')
    assert kw['image'] == 'serfriz/caddy-duckdns:latest'
    assert 'DUCKDNS_API_TOKEN=${DUCKDNS_API_TOKEN}' in kw['environment']
    cf = Path(f'{tmp}/Caddyfile').read_text()
    assert 'acme_dns duckdns {$DUCKDNS_API_TOKEN}' in cf
    print('caddy_svc() duckdns OK')

with tempfile.TemporaryDirectory() as tmp:
    kw = caddy_svc('ex.com', conf=f'{tmp}/Caddyfile', caddyfile=Caddyfile('ex.com').encode(), mount='./Caddyfile')
    assert './Caddyfile:/etc/caddy/Caddyfile' in kw['volumes']
    test_eq(Path(f'{tmp}/Caddyfile').read_text(), 'ex.com {\n\tencode\n\treverse_proxy app:5001\n}\n')
    caddy_svc('ex.com', conf=f'{tmp}/Other', save=False)
    assert not Path(f'{tmp}/Other').exists()
    print('caddy_svc() caddyfile, save and mount OK')

kw = caddy_svc('ex.com', conf='config/Caddyfile', save=False)
assert './config/Caddyfile:/etc/caddy/Caddyfile' in kw['volumes']
caddy_svc() basic OK
caddy_svc() cloudflared OK
caddy_svc() crowdsec OK
caddy_svc() crowdsec+cloudflared OK
caddy_svc() cloudflare-dns OK
caddy_svc() cloudflare-dns+crowdsec OK
caddy_svc() duckdns OK

cloudflared_svc returns the Cloudflare Tunnel service. The cloudflared container connects out to Cloudflare and carries your site’s traffic back over that connection, so the server needs no open inbound port. token_env is the value given to the container’s TUNNEL_TOKEN; the default, ${CF_TUNNEL_TOKEN}, makes Compose read the token from the host’s CF_TUNNEL_TOKEN variable. Where the tunnel sends traffic is normally set in the Cloudflare dashboard, and url passes it on the command line instead, for example url='http://caddy'.


source

cloudflared_svc

def cloudflared_svc(
    token_env:str='${CF_TUNNEL_TOKEN}', url:NoneType=None, **kw
):

Return a Cloudflare Tunnel service for Compose.svc; url sets where the tunnel sends traffic, such as http://caddy.

kw = cloudflared_svc()
assert kw['image'] == 'cloudflare/cloudflared:latest'
assert kw['command'] == 'tunnel --no-autoupdate run'
assert 'TUNNEL_TOKEN=${CF_TUNNEL_TOKEN}' in kw['environment']
print('cloudflared_svc() OK')

kw2 = cloudflared_svc(url='http://caddy')
assert kw2['command'] == 'tunnel --no-autoupdate run --url http://caddy'
print('cloudflared_svc() with url OK')
cloudflared_svc() OK
cloudflared_svc() with url OK

CrowdSec keeps a shared list of IP addresses known for attacks, and Caddy’s CrowdSec plugin asks a local CrowdSec agent about each visitor. crowdsec returns the agent service. collections are the CrowdSec rule sets it installs; the default covers Linux, Caddy and known HTTP exploits. The agent registers a bouncer, CrowdSec’s name for a client that enforces its decisions, called caddy, with the key from the host’s CROWDSEC_BOUNCER_KEY variable. caddy_svc(crowdsec=True) gives Caddy its key from CROWDSEC_API_KEY, so set both variables to the same value. The agent keeps its data and config in the crowdsec-db and crowdsec-config volumes, which the stack must declare.


source

crowdsec

def crowdsec(
    collections:NoneType=None, bouncer_key_env:str='CROWDSEC_BOUNCER_KEY', **kw
):

Return a CrowdSec agent service for Compose.svc, with the bouncer key for Caddy read from bouncer_key_env.

kw = crowdsec()
assert kw['image'] == 'crowdsecurity/crowdsec:latest'
assert any('crowdsecurity/caddy' in e for e in kw['environment'])
assert 'BOUNCER_KEY_caddy=${CROWDSEC_BOUNCER_KEY}' in kw['environment']
assert any('crowdsec-db' in v for v in kw['volumes'])
print('crowdsec() OK')

kw2 = crowdsec(collections=['crowdsecurity/linux', 'crowdsecurity/nginx'])
assert any('crowdsecurity/nginx' in e for e in kw2['environment'])
print('crowdsec() custom collections OK')
crowdsec() OK
crowdsec() custom collections OK

Example stacks

Five complete stacks for an app behind Caddy, from the simplest to the most locked down. Each one prints its Compose file. To run one, save it with dc.save('docker-compose.yml') and run docker compose up -d.

  • Stack A: Caddy fetches certificates itself, and ports 80 and 443 are open.
  • Stack B: a Cloudflare Tunnel carries the traffic, and no port is open.
  • Stack C: stack B with CrowdSec checking visitors.
  • Stack D: Caddy gets its certificate with a DNS-01 challenge through Cloudflare, with the ports open and no tunnel.
  • Stack E: stack D with CrowdSec.
tmp = tempfile.mkdtemp()

dc = (Compose()
    .svc('app', build='.', networks=['web'], restart='unless-stopped')
    .svc('caddy', **caddy_svc('myapp.example.com', port=5001, conf=f'{tmp}/Caddyfile'))
    .network('web', driver='bridge').volume('caddy_data').volume('caddy_config'))

d = dc.to_dict()
assert d['services']['caddy']['image'] == 'caddy:2'
assert '80:80' in d['services']['caddy']['ports']
print('=== Stack A: Direct (Caddy auto-TLS) ===')
print(dc)
=== Stack A: Direct (Caddy auto-TLS) ===
services:
  app:
    build: .
    networks:
    - web
    restart: unless-stopped
  caddy:
    image: caddy:2
    depends_on:
    - app
    ports:
    - 80:80
    - 443:443
    - 443:443/udp
    volumes:
    - /private/var/folders/kg/9vdw4mdd1fs58svgh4k1qhr09x7dqh/T/tmp2pn1i7ra/Caddyfile:/etc/caddy/Caddyfile
    - caddy_data:/data
    - caddy_config:/config
    networks:
    - web
    restart: unless-stopped
networks:
  web:
    driver: bridge
volumes:
  caddy_data: null
  caddy_config: null
tmp = tempfile.mkdtemp()
dc = (Compose()
    .svc('app', build='.', networks=['web'], restart='unless-stopped')
    .svc('caddy', **caddy_svc('myapp.example.com', port=5001, cloudflared=True, conf=f'{tmp}/Caddyfile'))
    .svc('cloudflared', **cloudflared_svc())
    .network('web').volume('caddy_data').volume('caddy_config'))

d = dc.to_dict()
assert 'ports' not in d['services']['caddy']
assert d['services']['cloudflared']['image'] == 'cloudflare/cloudflared:latest'
print('=== Stack B: Cloudflared (zero open ports) ===')
print(dc)
=== Stack B: Cloudflared (zero open ports) ===
services:
  app:
    build: .
    networks:
    - web
    restart: unless-stopped
  caddy:
    image: caddy:2
    depends_on:
    - app
    volumes:
    - /private/var/folders/kg/9vdw4mdd1fs58svgh4k1qhr09x7dqh/T/tmprvwce3po/Caddyfile:/etc/caddy/Caddyfile
    - caddy_data:/data
    - caddy_config:/config
    networks:
    - web
    restart: unless-stopped
  cloudflared:
    image: cloudflare/cloudflared:latest
    command: tunnel --no-autoupdate run
    environment:
    - TUNNEL_TOKEN=${CF_TUNNEL_TOKEN}
    networks:
    - web
    restart: unless-stopped
networks:
  web: null
volumes:
  caddy_data: null
  caddy_config: null
tmp = tempfile.mkdtemp()
dc = (Compose()
    .svc('app', build='.', networks=['web'], restart='unless-stopped')
    .svc('caddy', **caddy_svc('myapp.example.com', port=5001, crowdsec=True, cloudflared=True, conf=f'{tmp}/Caddyfile'))
    .svc('crowdsec', **crowdsec())
    .svc('cloudflared', **cloudflared_svc())
    .network('web')
    .volume('caddy_data').volume('caddy_config')
    .volume('crowdsec-db').volume('crowdsec-config'))

d = dc.to_dict()
assert d['services']['caddy']['image'] == 'serfriz/caddy-crowdsec:latest'
assert d['services']['crowdsec']['image'] == 'crowdsecurity/crowdsec:latest'
assert 'ports' not in d['services']['caddy']
print('=== Stack C: CrowdSec + cloudflared (zero open ports) ===')
print(dc)
=== Stack C: CrowdSec + cloudflared (zero open ports) ===
services:
  app:
    build: .
    networks:
    - web
    restart: unless-stopped
  caddy:
    image: serfriz/caddy-crowdsec:latest
    depends_on:
    - app
    volumes:
    - /private/var/folders/kg/9vdw4mdd1fs58svgh4k1qhr09x7dqh/T/tmp7hi9ftvr/Caddyfile:/etc/caddy/Caddyfile
    - caddy_data:/data
    - caddy_config:/config
    environment:
    - CROWDSEC_API_KEY=${CROWDSEC_API_KEY}
    networks:
    - web
    restart: unless-stopped
  crowdsec:
    image: crowdsecurity/crowdsec:latest
    volumes:
    - crowdsec-db:/var/lib/crowdsec/data
    - crowdsec-config:/etc/crowdsec
    environment:
    - COLLECTIONS=crowdsecurity/linux crowdsecurity/caddy crowdsecurity/http-cve
    - BOUNCER_KEY_caddy=${CROWDSEC_BOUNCER_KEY}
    networks:
    - web
    restart: unless-stopped
  cloudflared:
    image: cloudflare/cloudflared:latest
    command: tunnel --no-autoupdate run
    environment:
    - TUNNEL_TOKEN=${CF_TUNNEL_TOKEN}
    networks:
    - web
    restart: unless-stopped
networks:
  web: null
volumes:
  caddy_data: null
  caddy_config: null
  crowdsec-db: null
  crowdsec-config: null
tmp = tempfile.mkdtemp()

dc = (Compose()
    .svc('app', build='.', networks=['web'], restart='unless-stopped')
    .svc('caddy', **caddy_svc('myapp.example.com', port=5001, dns='cloudflare', email='me@example.com', conf=f'{tmp}/Caddyfile'))
    .network('web').volume('caddy_data').volume('caddy_config'))

d = dc.to_dict()
assert d['services']['caddy']['image'] == 'serfriz/caddy-cloudflare:latest'
assert '80:80' in d['services']['caddy']['ports']
assert 'CLOUDFLARE_API_TOKEN=${CLOUDFLARE_API_TOKEN}' in d['services']['caddy']['environment']
cf = Path(f'{tmp}/Caddyfile').read_text()
assert 'acme_dns cloudflare {$CLOUDFLARE_API_TOKEN}' in cf
print('=== Stack D: Cloudflare DNS-01 (wildcard cert, direct) ===')
print(dc)
print('--- Caddyfile ---')
print(cf)
=== Stack D: Cloudflare DNS-01 (wildcard cert, direct) ===
services:
  app:
    build: .
    networks:
    - web
    restart: unless-stopped
  caddy:
    image: serfriz/caddy-cloudflare:latest
    depends_on:
    - app
    ports:
    - 80:80
    - 443:443
    - 443:443/udp
    volumes:
    - /private/var/folders/kg/9vdw4mdd1fs58svgh4k1qhr09x7dqh/T/tmptw1nzplx/Caddyfile:/etc/caddy/Caddyfile
    - caddy_data:/data
    - caddy_config:/config
    environment:
    - CLOUDFLARE_API_TOKEN=${CLOUDFLARE_API_TOKEN}
    networks:
    - web
    restart: unless-stopped
networks:
  web: null
volumes:
  caddy_data: null
  caddy_config: null

--- Caddyfile ---
{
    email me@example.com
}
myapp.example.com {
    tls {
        acme_dns cloudflare {$CLOUDFLARE_API_TOKEN}
    }
    reverse_proxy app:5001
}
tmp = tempfile.mkdtemp()

dc = (Compose()
    .svc('app', build='.', networks=['web'], restart='unless-stopped')
    .svc('caddy', **caddy_svc('myapp.example.com', port=5001,
                              dns='cloudflare', crowdsec=True,
                              email='me@example.com', conf=f'{tmp}/Caddyfile'))
    .svc('crowdsec', **crowdsec())
    .network('web')
    .volume('caddy_data').volume('caddy_config')
    .volume('crowdsec-db').volume('crowdsec-config'))

d = dc.to_dict()
assert d['services']['caddy']['image'] == 'ghcr.io/buildplan/csdp-caddy:latest'
assert '80:80' in d['services']['caddy']['ports']
assert d['services']['crowdsec']['image'] == 'crowdsecurity/crowdsec:latest'
assert 'CLOUDFLARE_API_TOKEN=${CLOUDFLARE_API_TOKEN}' in d['services']['caddy']['environment']
assert 'CROWDSEC_API_KEY=${CROWDSEC_API_KEY}' in d['services']['caddy']['environment']
cf = Path(f'{tmp}/Caddyfile').read_text()
assert 'acme_dns cloudflare {$CLOUDFLARE_API_TOKEN}' in cf
assert 'crowdsec' in cf
print('=== Stack E: Cloudflare DNS + CrowdSec (full security, direct ports) ===')
print(dc)
print('--- Caddyfile ---')
print(cf)
=== Stack E: Cloudflare DNS + CrowdSec (full security, direct ports) ===
services:
  app:
    build: .
    networks:
    - web
    restart: unless-stopped
  caddy:
    image: ghcr.io/buildplan/csdp-caddy:latest
    depends_on:
    - app
    ports:
    - 80:80
    - 443:443
    - 443:443/udp
    volumes:
    - /private/var/folders/kg/9vdw4mdd1fs58svgh4k1qhr09x7dqh/T/tmp4y8f06cw/Caddyfile:/etc/caddy/Caddyfile
    - caddy_data:/data
    - caddy_config:/config
    environment:
    - CLOUDFLARE_API_TOKEN=${CLOUDFLARE_API_TOKEN}
    - CROWDSEC_API_KEY=${CROWDSEC_API_KEY}
    networks:
    - web
    restart: unless-stopped
  crowdsec:
    image: crowdsecurity/crowdsec:latest
    volumes:
    - crowdsec-db:/var/lib/crowdsec/data
    - crowdsec-config:/etc/crowdsec
    environment:
    - COLLECTIONS=crowdsecurity/linux crowdsecurity/caddy crowdsecurity/http-cve
    - BOUNCER_KEY_caddy=${CROWDSEC_BOUNCER_KEY}
    networks:
    - web
    restart: unless-stopped
networks:
  web: null
volumes:
  caddy_data: null
  caddy_config: null
  crowdsec-db: null
  crowdsec-config: null

--- Caddyfile ---
{
    email me@example.com
}
myapp.example.com {
    tls {
        acme_dns cloudflare {$CLOUDFLARE_API_TOKEN}
    }
    crowdsec {
        api_url http://crowdsec:8080
        api_key {$CROWDSEC_API_KEY}
    }
    reverse_proxy app:5001
}

Integration test: FastHTML, Caddy and cloudflared

This test starts a real stack and checks that the app can be reached over the internet. It is skipped in the docs build and by nbdev_test. To run it you need:

  • a Cloudflare Tunnel, created in the Cloudflare Zero Trust dashboard under Tunnels, with its token in the CF_TUNNEL_TOKEN environment variable;
  • a public hostname on that tunnel that sends traffic to http://caddy;
  • DOMAIN, set at the top of the cell, changed to that hostname.

The cell writes a FastHTML app, builds it with fasthtml_app, and starts the app, Caddy and cloudflared. It then requests https://DOMAIN every 10 seconds for up to two minutes and prints the container logs. Whether or not the check passes, it takes the stack down and removes the image.

DOMAIN = 'fastops.angalama.com'
# Compose reads CF_TUNNEL_TOKEN from the host environment.

app_dir = Path(tempfile.mkdtemp(dir='.'))
(app_dir / 'app.py').write_text('''\
from fasthtml.common import *
app, rt = fast_app()

@rt('/')
def get(): return Titled('dockeasy-proxy-test', P('Caddy + cloudflared ✓'))

serve()
''')
(app_dir / 'pyproject.toml').write_text('''\
[project]
name = "proxy-test"
version = "0.1.0"
dependencies = ["python-fasthtml", "starlette<0.46"]
''')
fasthtml_app().save(app_dir / 'Dockerfile')

tag = 'dockeasy-proxy-test:latest'

inf_dir = Path(tempfile.mkdtemp(dir='.'))
cf_path = str(inf_dir / 'Caddyfile')
dc_path = str(inf_dir / 'docker-compose.yml')

dc = (Compose()
    .svc('app', build=str(app_dir), image=tag, networks=['web'], restart='unless-stopped')
    .svc('caddy', **caddy_svc(DOMAIN, cloudflared=True, conf=cf_path))
    .svc('cloudflared', **cloudflared_svc(url='http://caddy'))
    .network('web').volume('caddy_data').volume('caddy_config'))

print(dc)
print('--- Caddyfile ---')
print(Path(cf_path).read_text())

try:
    dc.up(path=dc_path)
    print('Waiting for cloudflared tunnel to connect...')
    html = None
    for i in range(12):
        time.sleep(10)
        try: html = urlread(f'https://{DOMAIN}'); break
        except Exception as e: print(f'  [{(i+1)*10}s] not ready: {e}')
    print('=== container logs ===')
    print(dc.logs(path=dc_path))
    assert html and 'dockeasy-proxy-test' in html, f'Unexpected response: {html[:200] if html else "no response"}'
    print(f'✓ App reachable at https://{DOMAIN}')
finally:
    dc.down(path=dc_path, v=True, remove_orphans=True)
    rmi(tag, force=True)
    print('Cleaned up.')
services:
  app:
    image: dockeasy-proxy-test:latest
    build: /Users/71293/code/dockeasy/nbs/tmpode386ks
    networks:
    - web
    restart: unless-stopped
  caddy:
    image: caddy:2
    depends_on:
    - app
    volumes:
    - /Users/71293/code/dockeasy/nbs/tmp881ik_hr/Caddyfile:/etc/caddy/Caddyfile
    - caddy_data:/data
    - caddy_config:/config
    networks:
    - web
    restart: unless-stopped
  cloudflared:
    image: cloudflare/cloudflared:latest
    command: tunnel --no-autoupdate run --url http://caddy
    environment:
    - TUNNEL_TOKEN=${CF_TUNNEL_TOKEN}
    networks:
    - web
    restart: unless-stopped
networks:
  web: null
volumes:
  caddy_data: null
  caddy_config: null

--- Caddyfile ---
http://fastops.angalama.com {
    reverse_proxy app:5001
}
Waiting for cloudflared tunnel to connect...
=== container logs ===
caddy-1        | {"level":"info","ts":1774238518.5918498,"msg":"maxprocs: Leaving GOMAXPROCS=2: CPU quota undefined"}
cloudflared-1  | 2026-03-23T04:01:58Z INF Starting tunnel tunnelID=8dc509a8-a295-46d0-bf48-95f619ca930b
caddy-1        | {"level":"info","ts":1774238518.591999,"msg":"GOMEMLIMIT is updated","GOMEMLIMIT":1848873369,"previous":9223372036854775807}
caddy-1        | {"level":"info","ts":1774238518.592026,"msg":"using config from file","file":"/etc/caddy/Caddyfile"}
caddy-1        | {"level":"info","ts":1774238518.5920372,"msg":"adapted config to JSON","adapter":"caddyfile"}
app-1          | INFO:     Will watch for changes in these directories: ['/app']
caddy-1        | {"level":"warn","ts":1774238518.5920472,"msg":"Caddyfile input is not formatted; run 'caddy fmt --overwrite' to fix inconsistencies","adapter":"caddyfile","file":"/etc/caddy/Caddyfile","line":3}
app-1          | INFO:     Uvicorn running on http://0.0.0.0:5001 (Press CTRL+C to quit)
app-1          | INFO:     Started reloader process [1] using WatchFiles
app-1          | Link: http://localhost:5001
app-1          | INFO:     Started server process [7]
caddy-1        | {"level":"info","ts":1774238518.5930362,"logger":"admin","msg":"admin endpoint started","address":"localhost:2019","enforce_origin":false,"origins":["//[::1]:2019","//127.0.0.1:2019","//localhost:2019"]}
caddy-1        | {"level":"warn","ts":1774238518.5931695,"logger":"http.auto_https","msg":"server is listening only on the HTTP port, so no automatic HTTPS will be applied to this server","server_name":"srv0","http_port":80}
app-1          | INFO:     Waiting for application startup.
caddy-1        | {"level":"info","ts":1774238518.5932415,"logger":"tls.cache.maintenance","msg":"started background certificate maintenance","cache":"0x76986d100200"}
caddy-1        | {"level":"warn","ts":1774238518.5933907,"logger":"http","msg":"HTTP/2 skipped because it requires TLS","network":"tcp","addr":":80"}
cloudflared-1  | 2026-03-23T04:01:58Z INF Version 2026.2.0 (Checksum 5620827b47ba8b47b20649f810e00a7a4e25da71ef66c30bec2b94eeb5c99689)
cloudflared-1  | 2026-03-23T04:01:58Z INF GOOS: linux, GOVersion: go1.24.13, GoArch: arm64
caddy-1        | {"level":"warn","ts":1774238518.5933926,"logger":"http","msg":"HTTP/3 skipped because it requires TLS","network":"tcp","addr":":80"}
cloudflared-1  | 2026-03-23T04:01:58Z INF Settings: map[no-autoupdate:true url:http://caddy]
cloudflared-1  | 2026-03-23T04:01:58Z INF Generated Connector ID: 2274aaf4-28ed-4c2b-a516-5303a48fba5b
caddy-1        | {"level":"info","ts":1774238518.5933936,"logger":"http.log","msg":"server running","name":"srv0","protocols":["h1","h2","h3"]}
app-1          | INFO:     Application startup complete.
caddy-1        | {"level":"info","ts":1774238518.593471,"msg":"autosaved config (load with --resume flag)","file":"/config/caddy/autosave.json"}
app-1          | INFO:     172.19.0.4:54496 - "GET / HTTP/1.1" 200 OK
caddy-1        | {"level":"info","ts":1774238518.5934741,"msg":"serving initial configuration"}
caddy-1        | {"level":"info","ts":1774238518.595158,"logger":"tls","msg":"cleaning storage unit","storage":"FileStorage:/data/caddy"}
caddy-1        | {"level":"info","ts":1774238518.6006067,"logger":"tls","msg":"finished cleaning storage units"}
cloudflared-1  | 2026-03-23T04:01:58Z INF Initial protocol quic
cloudflared-1  | 2026-03-23T04:01:58Z INF ICMP proxy will use 172.19.0.3 as source for IPv4
cloudflared-1  | 2026-03-23T04:01:58Z INF ICMP proxy will use ::1 in zone lo as source for IPv6
cloudflared-1  | 2026-03-23T04:01:58Z INF ICMP proxy will use 172.19.0.3 as source for IPv4
cloudflared-1  | 2026-03-23T04:01:58Z INF ICMP proxy will use ::1 in zone lo as source for IPv6
cloudflared-1  | 2026-03-23T04:01:58Z INF Starting metrics server on [::]:20241/metrics
cloudflared-1  | 2026-03-23T04:01:58Z INF Tunnel connection curve preferences: [X25519MLKEM768 CurveP256] connIndex=0 event=0 ip=198.41.192.57
cloudflared-1  | 2026/03/23 04:01:58 failed to sufficiently increase receive buffer size (was: 208 kiB, wanted: 7168 kiB, got: 416 kiB). See https://github.com/quic-go/quic-go/wiki/UDP-Buffer-Sizes for details.
cloudflared-1  | 2026-03-23T04:01:59Z INF Registered tunnel connection connIndex=0 connection=852faa5f-2fb0-41a8-8e57-b46aa8fa60c8 event=0 ip=198.41.192.57 location=mel01 protocol=quic
cloudflared-1  | 2026-03-23T04:01:59Z INF Tunnel connection curve preferences: [X25519MLKEM768 CurveP256] connIndex=1 event=0 ip=198.41.200.63
cloudflared-1  | 2026-03-23T04:01:59Z INF Registered tunnel connection connIndex=1 connection=23b5eaeb-9af2-45f7-af78-a2f4474c6491 event=0 ip=198.41.200.63 location=syd05 protocol=quic
cloudflared-1  | 2026-03-23T04:02:00Z INF Tunnel connection curve preferences: [X25519MLKEM768 CurveP256] connIndex=2 event=0 ip=198.41.192.107
cloudflared-1  | 2026-03-23T04:02:00Z INF Registered tunnel connection connIndex=2 connection=f570338f-b8ae-4efa-a350-5fbb169591ce event=0 ip=198.41.192.107 location=mel02 protocol=quic
cloudflared-1  | 2026-03-23T04:02:01Z INF Tunnel connection curve preferences: [X25519MLKEM768 CurveP256] connIndex=3 event=0 ip=198.41.200.113
cloudflared-1  | 2026-03-23T04:02:02Z INF Registered tunnel connection connIndex=3 connection=8532097b-e13a-435c-85f8-453f231e8f9e event=0 ip=198.41.200.113 location=adl01 protocol=quic
✓ App reachable at https://fastops.angalama.com
Cleaned up.