[Refactor/Chore] Support Caddy as an alternative reverse proxy in docker-compose (prototype tested for parity)

Aperta
#46,728 4 commenti 1 reazione 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
35/100
Tipo di issue
Refactoring
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
docker, docker-compose, nginx

Direzione di ricerca

Start with docker/docker-compose-template.yaml, the files under docker/nginx/, and docker/tests/test_compose_environment.py; then read docker/README.md and the certbot and self-hosting docs listed in the issue. Confirm with maintainers whether Caddy should replace the default proxy or begin as an opt-in profile, and how to handle existing NGINX_* settings and certbot. Done means the agreed Compose setup, docs, tests, and CI path filter are updated while preserving the proxy behavior described in the issue.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

💪 enhancement Configuration refactor
Self Checks
  • I have read the Contributing Guide and Language Policy.
  • This is only for refactors or chores; if you would like to ask a question, please head to Discussions.
  • I have searched for existing issues search for existing issues, including closed ones.
  • I confirm that I am using English to submit this report, otherwise it will be closed.
  • 【中文用户 & Non English User】请使用英语提交,否则会被关闭 :)
  • Please do not modify this template :) and fill in all the required fields.
Description

Proposal: replace the bundled nginx service in docker/docker-compose-template.yaml with Caddy. The five files under docker/nginx/ (three templates, conf.d/default.conf.template, and the envsubst entrypoint) become one Caddyfile plus a short entrypoint. The existing NGINX_* variables keep working, so users' .env / nginx.env files need no change.

I built a prototype and tested it against the current docker/nginx config (main @ 92c4d2d5). The same requests went through both proxies to the same upstreams, and I compared what the client got back and what the upstream received:

  1. Mock upstreams. Four small servers stand in for api, web, plugin_daemon and api_websocket, plus a Werkzeug ProxyFix(x_for=1, x_port=1) replay. This checks how Dify itself interprets each request.
  2. A real Dify 1.19.0 stack. I set it up and ran the checks through Caddy: setup, login, DSL import, publish, API keys. I then ran the same checks through both proxies.

Results

Check nginx (current) Caddy prototype
Routing of 26 paths (/console/api, /api, /v1, /openapi, /files, /mcp, /triggers, /callbacks/human-input/v2/im/, /e/, /socket.io/, /explore, /, prefix look-alikes such as /apifoo and /v1x, .. and %61pi paths, ACME webroot) — identical
What Dify sees after ProxyFix (client IP, Host, port), with Host with or without a port, IPv6 Host, and spoofed X-Forwarded-For / -Port — identical
Dify-Hook-Url on /e/ (http, https, IPv6 Host) — identical
SSE / chunked streaming (events 1 s apart; real /v1/workflows/run with three 1 s HTTP nodes) events at 0/1/2/3 s events at 0/1/2/3 s
Body limit (NGINX_CLIENT_MAX_BODY_SIZE=100M) 100 MiB accepted, 100 MiB + 1 B → 413 same (also chunked bodies)
Read timeout (set to 6 s, upstream stalls 10 s) 504 after 6 s 504 after 6 s
WebSocket via /socket.io/; socket.io polling on real 1.19.0 works works
Real 1.19.0: /signin, /_next/static, /apps and /install redirects, /console/api/system-features, /v1/parameters, /e/<hook> (plugin daemon 404), 5 MB upload, 120 MB upload → 413 — identical
TLS 1.2 / 1.3 with operator-supplied certificate works works
HTTP/2 on the TLS port not negotiated (the template has no http2) h2, served by Go's net/http

The remaining differences are minor. Caddy drops a client-sent X-Forwarded-Host, which nginx passes through; Dify does not trust that header either way. Caddy sends an empty X-Forwarded-Port when the Host has no port, which ProxyFix ignores. Caddy also allows WebSocket upgrades on every route, and it sends no Server header (nginx sends its version). An HTTP/1.0 request without a Host header reaches the upstream with Host _ through nginx and api:5001 through Caddy.

Pitfalls the prototype handles. A straight translation got each of these wrong:

  • Caddy reads the size 100M as 10^8 bytes, and in nginx it means 100 MiB. A 99 MiB upload was rejected until the entrypoint translated k/m/g to KiB/MiB/GiB.
  • Caddy's path matcher is case-insensitive, so /API/x went to the API instead of the web app. nginx prefix locations are case-sensitive, so the prototype uses path_regexp.
  • transport http { read_timeout } on a reused upstream connection makes Go retry a timed-out GET. The upstream received the same GET twice, and the client waited 12 s instead of 6 s. The prototype uses response_header_timeout instead.
  • {host} strips the IPv6 brackets, so Dify-Hook-Url uses a map.
  • nginx answers /e with a 301 to /e/, and the prototype does the same with an explicit redir.
Motivation
  1. The bug class. nginx keeps shipping memory-corruption fixes in its HTTP/2 and HTTP/3 code; this week's advisory is CVE-2026-123007 (HTTP/2 flow control, fixed in 1.31.9 / 1.30.7). The default Dify config is not exposed, because it does not enable http2, and I confirmed that with ALPN above. Users who turn HTTP/2 on are exposed, and image: nginx:latest only picks up fixes when users re-pull. A memory-safe proxy still needs updates, but its vulnerabilities are far less likely to allow remote code execution. For example, the Go HTTP/2 issues of 2023–2024 (Rapid Reset, CONTINUATION flood) were denial-of-service bugs.
  2. Upstream connection reuse. The current template uses proxy_pass http://$variable to get Docker DNS re-resolution. That form has no upstream keepalive pool, so every request opens a new TCP connection and leaves a TIME_WAIT socket in the nginx container. In a short benchmark against mock upstreams, nginx returned 502 for every request after the first 28,231. That number is exactly the container's ephemeral port range, and the log shows connect() ... failed (99: Cannot assign requested address). At 100 concurrent requests, Caddy served everything with about 33 pooled connections and roughly 3x the throughput. This was on Docker Desktop on a Mac, so only the relative numbers matter. This one is also fixable in nginx (upstream blocks with keepalive plus resolve), so I would not treat it as the main reason to switch.
  3. HTTPS without a certbot sidecar. Caddy can obtain and renew certificates itself. The prototype keeps today's behaviour (operator-supplied certificates plus the optional certbot webroot), so this would be a later, opt-in step.

Costs and trade-offs

  • Users who edited docker/nginx/conf.d lose those edits. The most common case is the real-IP snippet documented in docker/README.md. Suggestion: ship Caddy as the default and keep nginx behind a Compose profile for one or two releases, with a migration note that maps each common snippet to its Caddyfile equivalent.
  • Docs to update: docker/README.md (body size, client IP / Cloudflare, troubleshooting commands), docker/certbot/README.md, and the self-hosting docs.
  • Tests: docker/tests/test_compose_environment.py references the nginx service and its variables. The docker/nginx/** path filter in main-ci.yml would move.
  • Memory: Caddy used about 39 MiB vs 24 MiB for nginx in the test container.
  • NGINX_SSL_PROTOCOLS uses nginx syntax. The prototype pins TLS 1.2/1.3, which is also Caddy's default floor.
Additional Context

Questions for maintainers before a PR:

  1. Is replacing the default proxy acceptable, or should Caddy start as an opt-in profile?
  2. Keep the NGINX_* variable names, or introduce neutral names (e.g. PROXY_*) and read the old ones as fallbacks?
  3. Is moving HTTPS to Caddy's built-in ACME (dropping the certbot profile) welcome now, or later?

I am happy to open the PR once the direction is agreed.

Prototype Caddyfile
{
	admin off
	# Certificates are supplied by the operator (same as nginx today); no ACME, no redirects.
	auto_https off
	servers {
		protocols h1 h2
	}
}

(dify_upstream) {
	reverse_proxy {args[0]} {
		# nginx: proxy_buffering off
		flush_interval -1
		# nginx maps X-Forwarded-Port from the Host header so Werkzeug ProxyFix(x_port=1)
		# keeps the external port; an empty value is ignored by ProxyFix.
		header_up X-Forwarded-Port {http.request.port}
		# Dify trusts only X-Forwarded-For/-Port; never forward a client-supplied host.
		header_up -X-Forwarded-Host
		header_up -Via
		# nginx replaces the upstream Server header; do not reveal the app server.
		header_down -Server
		transport http {
			# Not read_timeout: on a reused upstream connection Go retries a timed-out GET, so the backend sees it twice.
			response_header_timeout {$DIFY_PROXY_READ_TIMEOUT}
			write_timeout {$DIFY_PROXY_SEND_TIMEOUT}
		}
	}
}

(dify_routes) {
	request_body {
		max_size {$DIFY_PROXY_MAX_BODY_SIZE}
	}

	import acme-{$NGINX_ENABLE_CERTBOT_CHALLENGE:false}.caddy

	# nginx prefix locations are case-sensitive; Caddy's path matcher is not, so use a regexp.
	@api path_regexp ^/(console/api|api|v1|openapi|files|mcp|triggers|callbacks/human-input/v2/im/)
	handle @api {
		import dify_upstream api:5001
	}

	@socketio path_regexp ^/socket\.io/
	handle @socketio {
		import dify_upstream {$NGINX_SOCKET_IO_UPSTREAM:api_websocket:5001}
	}

	# nginx answers "/e" with a 301 to "/e/" because of the "location /e/" proxy block.
	redir /e /e/ 301

	@hook path_regexp ^/e/
	handle @hook {
		# nginx: $scheme://$host$request_uri ($host has no port; IPv6 keeps brackets).
		map {http.request.host} {dify_hook_host} {
			~^(.*:.*)$ "[${1}]"
			default {http.request.host}
		}
		request_header Dify-Hook-Url {scheme}://{dify_hook_host}{uri}
		import dify_upstream plugin_daemon:5002
	}

	handle {
		import dify_upstream web:3000
	}

	header -Via
}

http://:{$NGINX_PORT:80} {
	import dify_routes
}

import https-{$NGINX_HTTPS_ENABLED:false}.caddy

https-true.caddy (loaded when NGINX_HTTPS_ENABLED=true; https-false.caddy is empty):

https://:{$NGINX_SSL_PORT:443} {
	tls /etc/ssl/{$NGINX_SSL_CERT_FILENAME:dify.crt} /etc/ssl/{$NGINX_SSL_CERT_KEY_FILENAME:dify.key} {
		protocols tls1.2 tls1.3
	}
	import dify_routes
}

acme-true.caddy serves /.well-known/acme-challenge/* from /var/www/html for the certbot profile.

Entrypoint (translates nginx units)
#!/bin/sh
set -eu
# nginx sizes: 100M = 100 MiB (binary), k/m/g suffixes, or bare bytes.
to_size() {
	v=$1; n=${v%[kKmMgG]}
	case ${v#"$n"} in
		k | K) echo "${n}KiB" ;;
		m | M) echo "${n}MiB" ;;
		g | G) echo "${n}GiB" ;;
		*) echo "$v" ;;
	esac
}
# nginx times: a bare number means seconds.
to_duration() { case $1 in *[!0-9]*) echo "$1" ;; *) echo "${1}s" ;; esac; }

DIFY_PROXY_MAX_BODY_SIZE=$(to_size "${NGINX_CLIENT_MAX_BODY_SIZE:-100M}")
DIFY_PROXY_READ_TIMEOUT=$(to_duration "${NGINX_PROXY_READ_TIMEOUT:-3600s}")
DIFY_PROXY_SEND_TIMEOUT=$(to_duration "${NGINX_PROXY_SEND_TIMEOUT:-3600s}")
export DIFY_PROXY_MAX_BODY_SIZE DIFY_PROXY_READ_TIMEOUT DIFY_PROXY_SEND_TIMEOUT
exec caddy run --config /etc/caddy/Caddyfile --adapter caddyfile
Test setup
  • Caddy v2.11.9 (caddy:2-alpine), nginx 1.31.9 (nginx:latest, using the unmodified docker/nginx files and entrypoint from main).
  • Mock upstreams: aiohttp, one per Dify service name, echoing the method, path, headers and peer; plus SSE, chunked, slow, upload and WebSocket endpoints.
  • ProxyFix replay: werkzeug 3.1.3, ProxyFix(x_for=1, x_port=1), matching api/extensions/ext_proxy_fix.py.
  • Real stack: community 1.19.0 images; both proxies attached to the Compose network with NGINX_SOCKET_IO_UPSTREAM=api:5001, because 1.19.0 has no api_websocket service.
  • Throughput: hey, 20k–40k GETs at 20/50/100 concurrency, with each run started at < 1,000 TIME_WAIT sockets.
Lingua principale
Python
Stelle
162k
Fork
25.6k
Merge medio
15h 9m
PR unite (30g)
606

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di langgenius/dify

Tutte le issue di langgenius/dify

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.