Understanding Caddy’s modular architecture and how its components work together
Caddy is built on a powerful, extensible architecture that emphasizes modularity, configuration flexibility, and automatic HTTPS. This page explains how Caddy’s core components work together to deliver a production-ready web server.
From caddy.go:389-468, the run() function orchestrates the entire process:
View the run() function logic
// 1. Create context and provision modulesctx, err := provisionContext(newCfg, start)// 2. Provision admin routers which may need access to other appserr = ctx.cfg.Admin.provisionAdminRouters(ctx)// 3. Start all appsstarted := make([]string, 0, len(ctx.cfg.apps))for name, a := range ctx.cfg.apps { err := a.Start() if err != nil { // Stop already-started apps on failure for _, otherAppName := range started { ctx.cfg.apps[otherAppName].Stop() } return fmt.Errorf("%s app module: start: %v", name, err) } started = append(started, name)}
If any app fails to start, Caddy stops all previously-started apps and cleans up provisioned modules to prevent resource leaks.
The Admin API provides runtime control over Caddy’s configuration:
admin.go:67-86
type AdminConfig struct { // If true, the admin endpoint will be completely disabled Disabled bool `json:"disabled,omitempty"` // The address to which the admin endpoint's listener should bind itself // Default: localhost:2019 Listen string `json:"listen,omitempty"` // If true, CORS headers will be emitted EnforceOrigin bool `json:"enforce_origin,omitempty"` // The list of allowed origins/hosts for API requests Origins []string `json:"origins,omitempty"` // Options pertaining to configuration management Config *ConfigSettings `json:"config,omitempty"`}
Caddy has an event system for monitoring and reacting to changes:
caddy.go:1070-1092
type Event struct { // If non-nil, the event has been aborted Aborted error // The data associated with the event Data map[string]any id uuid.UUID ts time.Time name string origin Module}
Events are emitted for:
Certificate renewals
Server starts/stops
Config changes
Custom module events
Events are experimental and follow the CloudEvents specification for compatibility with external systems.