Virtualization

Caddy Reverse Proxy 502 Errors: Check Self-Hosted Upstreams Safely

The Back Room Tech Staff · Edited by Aseem Kishore
19 min read

The Back Room Tech is reader-supported. We may earn a commission when you buy through links on our site. Learn more.

Trace Caddy reverse proxy 502 errors by testing the exact upstream from Caddy’s network context. First, record the version of the executable or container that’s serving requests.

A 502 can mean Caddy couldn’t complete an upstream exchange, but the application can return it too. Check the active route and application listener, then match both sides’ logs.

Prerequisites

You’ll need access to the existing Caddy deployment and upstream application. This guide covers Caddy 2 on Linux and Windows. Use the commands for the environment you’re checking.

Before running checks, confirm:

  • The operating system and version on both machines, if they’re separate.
  • Caddy’s process, executable path or container image identity, and deployment method.
  • The configuration source, including any adapter, mounted files, or API-managed configuration.
  • Permission to inspect listeners and read relevant logs.
  • A documented application endpoint that won’t change data when probed.
  • curl where you’ll run HTTP checks. Windows examples use curl.exe explicitly.
  • ss for Linux TCP listener checks, or PowerShell’s Get-NetTCPConnection on Windows.

You don’t need new hardware. The same checks apply to a Raspberry Pi, a mini PC, or a larger server.

Check the deployed build’s help and the official Caddy documentation before running management commands. A custom build can include modules that another caddy executable lacks.

Quick Diagnosis for Caddy Reverse Proxy 502 Errors

SymptomFirst checkWhat it establishes
Connection refusedApplication listener at the exact address and portWhether that destination accepts TCP connections
Host probe works, container failsCaddy’s network membership and upstream nameWhether both tests use the same network path
no such hostName resolution inside Caddy’s environmentWhether Caddy can resolve the configured name
Connection timeoutFailure stage and application logsWhether the delay occurs before or after connection
Upstream certificate errorScheme, trust chain, and certificate identityWhether upstream HTTPS can be verified
Direct request works, proxy failsPath, Host, authentication, method, and bodyWhether the requests match
Intermittent resets or upload failuresTimestamped logs and exact buildWhether failures track restarts or request traits

1. Record the process and active route

Start with a short deployment record:

ItemRecord
Running buildVersion output from the serving executable or container
DeploymentNative process, service, or confirmed container runtime
IdentityExecutable path or image ID/digest
ConfigurationSource path, adapter, mounts, and management method
Public requestHostname, path, method, and UTC timestamp
UpstreamExact hostname/address, port, and protocol
Network contextHost, container, or other isolated environment

A configuration file on disk doesn’t prove the process loaded it. The service might use another path, a mounted file, generated JSON, or configuration loaded through Caddy’s administration API.

Check startup arguments, the service definition, and deployment records. For API-managed setups, inspect the running configuration through the existing protected local administration channel. Treat configuration exports as sensitive.

Don’t expose the administration API to collect this information.

2. Establish who produced the 502

Match one failing request with Caddy’s runtime logs and the application’s logs. Use the same timezone, preferably UTC.

A Caddy upstream dial or TLS error identifies the stage where Caddy observed a failure; the upstream service or network path can still be responsible. An application log showing a 502 is another clue, rather than proof that it generated the response seen by the client. Correlate Caddy’s access and runtime logs, application logs, timestamps and response details before assigning response provenance.

An access-log status alone doesn’t settle this. Neither does a Server response header.

If the upstream itself returns 502, check that application’s dependencies and logs. Changing Caddy’s destination won’t repair a failed dependency inside the application.

3. Probe one safe endpoint from Caddy’s context

First, enter the environment where Caddy makes upstream connections. For containers, confirm the runtime, container name, network membership, and mounts. Then use the runtime’s execution mechanism.

Run this Bash probe only where curl is already available:

read -r -p "Exact upstream URL for a documented safe endpoint: " upstream_url

# Limit connection establishment to 5 seconds and the whole request to 10 seconds.
# Discard the body and report the received HTTP status.
curl --connect-timeout 5 --max-time 10 \
  --silent --show-error \
  --output /dev/null \
  --write-out 'HTTP %{http_code}\n' \
  "$upstream_url"

Expected results depend on the failure:

  • An HTTP status means an HTTP exchange occurred for this request.
  • A 401 or 403 proves a response arrived, but doesn’t prove application health.
  • A redirect proves the endpoint responded, but doesn’t validate its destination.
  • A 502 can be the upstream’s own response.
  • HTTP 000 means curl didn’t receive an HTTP status. Read its accompanying error.

Don’t add --location initially. Following redirects can hide which endpoint answered.

A safe GET still creates logs and uses resources. Use a documented read-only endpoint, and keep probes bounded. Don’t replay a payment, import, or upload to test basic connectivity.

Illustrative bounded upstream connectivity probe in the Caddy network context

Common Issues and Solutions

4. Problem: Caddy reports connection refused

Symptoms

  • Requests return 502 immediately.
  • Caddy logs include connect: connection refused.
  • The application recently restarted or changed ports.

Cause

The target address and port aren’t accepting the connection. A stopped application, wrong port, binding mismatch, or explicit network rejection can cause this.

Solution

  • Read the exact upstream from the active route.
  • Inspect listeners where the application runs.
  • Compare the listener’s address, port, and IP family with Caddy’s destination.
  • Read the application’s startup logs for binding failures.
  • Correct the application or destination based on that evidence.

For Linux TCP listeners:

ss -ltnp

Here, -l selects listening sockets, -t selects TCP, and -n keeps numeric addresses. The -p flag requests process details. Some process details require elevated privileges.

Inspect the Local Address:Port column. A listener on 127.0.0.1:8000 differs from one on a private interface or [::1]:8000.

This command covers TCP listeners. Use transport-specific checks if your upstream uses a Unix socket.

Verification

Repeat the bounded probe from Caddy’s environment. Then check the original public request after applying any validated routing correction.

A listener proves the socket exists. It doesn’t prove the application can handle the requested path.

5. Problem: The application works on the host but containerized Caddy returns 502

Symptoms

  • A host-side request succeeds.
  • The same destination fails from Caddy’s container.
  • The route contains localhost or 127.0.0.1.

Cause

Loopback belongs to a network context. Inside a normally isolated container, localhost identifies that container.

It doesn’t identify another container or automatically identify the host. Explicitly shared networking can change this, so inspect the actual deployment.

Solution

  • Confirm the runtime and both container identities.
  • Inspect their network membership.
  • Confirm the application’s internal listening port.
  • Check whether the application name resolves from Caddy’s container.
  • Probe the resolved service through the intended private network.

Suppose inspection confirms both containers share a suitable network. The application has the service name app and listens internally on port 8000.

The relevant upstream would be:

# Within the confirmed source Caddyfile's site block.
reverse_proxy app:8000

A host-published port can differ from the application’s internal port. Use the destination supported by the actual network setup.

Don’t publish a new upstream port just to make troubleshooting easier. A private container network avoids that exposure, but depends on service discovery and network membership.

Verification

Run the safe HTTP probe inside Caddy’s network context. Confirm it reaches the intended application, then test through Caddy.

A successful host probe remains useful evidence. It only describes the host’s path.

6. Problem: The application listens only on loopback

Symptoms

  • Local requests work where the application runs.
  • Requests from Caddy on another host or network context fail.
  • Listener inspection shows 127.0.0.1 or ::1.

Cause

A loopback listener generally accepts traffic only from its own network context.

Solution

First, decide whether loopback fits the setup:

  • If Caddy and the application share the host context, loopback can be correct.
  • If they use separate contexts, choose a suitable private binding or supported network setup.
  • If the application must listen on all interfaces, keep firewall and network restrictions.

Change the application’s documented bind setting only after confirming the required interface. 0.0.0.0 accepts IPv4 connections across available interfaces, so review exposure before using it.

Verification

Inspect the listener again in the application’s environment. Probe its intended private destination from Caddy, then check through the public route.

7. Problem: Caddy logs no such host

Symptoms

  • Caddy reports a lookup failure.
  • A service name works in one environment but fails in another.
  • The problem follows a network or deployment change.

Cause

Caddy can’t resolve the configured upstream hostname. Common causes include a typo, missing network membership, or resolver failure.

Solution

  • Compare the active upstream name with the deployed service name.
  • Confirm Caddy belongs to the network providing that name.
  • Use an available lookup tool inside Caddy’s environment.
  • Compare the returned address with the intended application’s address.
  • Check resolver configuration if unrelated names also fail.

The bounded curl probe also reports name-resolution failures. A successful lookup proves resolution, but doesn’t prove the returned destination is correct or reachable.

Avoid replacing a service name with a temporary container IP. That can work until the next deployment changes the address.

Verification

Confirm resolution from Caddy’s context, then repeat the HTTP probe. Check that the lookup error disappears from the matching request logs.

8. Problem: Connections time out

Symptoms

  • Requests pause before returning 502.
  • Logs include a timeout or deadline error.
  • Some upstreams work while one destination hangs.

Cause

A timeout describes a stage that didn’t finish. It doesn’t identify the underlying fault.

Solution

Locate the stage first:

StageEvidence to inspectNext action
Name lookupResolver errors before a connection attemptCheck naming and resolver access
TCP connectionConnect timeout without an accepted connectionCheck destination, routing, and firewall behavior
TLS negotiationTLS handshake timeoutCheck protocol and upstream TLS service
Response handlingConnection succeeds, then response stallsCheck application workload and dependencies

Match a bounded probe with application logs. A missing application request can point to a path problem, but incomplete logs can leave the same gap.

If the application logs the request and then stalls, check its processing and dependencies.

Verification

Repeat one safe request after the evidence-based correction. Confirm both the response and the matching application log.

I’d skip timeout changes unless the application has a documented need for longer processing. A larger timeout can make a broken request occupy resources longer.

9. Problem: Upstream HTTPS fails with certificate or protocol errors

Symptoms

  • Caddy logs an x509 error.
  • TLS negotiation fails before an application response.
  • Logs say an HTTP response arrived where HTTPS was expected.

Cause

There are two separate connections:

  • The visitor’s connection to Caddy.
  • Caddy’s connection to the upstream.

A valid public certificate doesn’t validate the second connection. The upstream scheme, trusted issuer, certificate identity, and validity all matter.

Solution

  • Confirm whether the exact application port serves HTTP or HTTPS.
  • Check the upstream certificate’s names, chain, and validity.
  • Confirm Caddy trusts the required issuer.
  • Check the TLS server name used for verification.
  • Check the HTTP Host value expected by the application.

These example routes select different upstream protocols:

# Within the confirmed source Caddyfile's site block.
reverse_proxy http://app:8000
# Within the confirmed source Caddyfile's site block.
reverse_proxy https://app.internal.example:8443

For HTTPS reached through an IP address, the certificate may identify a DNS name instead. The HTTP transport’s tls_server_name setting handles TLS identity when your deployed build supports it.

The HTTP Host header is separate from TLS certificate identity and can affect application routing after TLS succeeds. The current reverse-proxy reference says Caddy v2.11.0 and later automatically set Host to the HTTPS upstream host. Older builds can require different configuration; check the deployed version before adding an override.

Use the reverse proxy transport reference and the release notes for your build. Configure internal certificate trust with that version’s supported syntax.

Don’t use a blanket tls_insecure_skip_verify fix. It removes the verification needed to establish the upstream’s identity.

Verification

Repeat an HTTPS probe without bypassing verification, then check through Caddy.

Curl and Caddy can have different trust stores and settings. Curl success proves curl’s exchange succeeded. Caddy’s logs must confirm its own exchange.

10. Problem: A direct request works, but the proxied request fails

Symptoms

  • A health endpoint responds directly.
  • A particular application path still returns 502.
  • Failures depend on authentication, method, or request size.

Cause

The successful probe may differ from the failing request.

Solution

Compare these fields:

FieldCheck
Network contextDid both requests originate where Caddy connects?
DestinationSame address, port, and protocol?
PathSame path after any rewrite?
TLS identitySame trusted issuer and server name?
HTTP HostSame application virtual host?
AuthenticationSame required access context?
Method and bodySame request type and relevant body traits?

Start with a request that won’t change data and isolates the difference. Keep authentication enabled. Handle credentials through the application’s established secure workflow.

Don’t put tokens or cookies into screenshots or shared command history.

Verification

Check the original failing request once it’s safe to repeat. A successful /health request doesn’t validate an upload or an authenticated application route.

11. Problem: Manual checks pass, but health checks reject the upstream

Symptoms

  • A direct request returns a response.
  • Caddy considers the upstream unavailable.
  • Existing health checks use another endpoint or port.

Cause

Health checks can test a different path, port, method, or expected response. Authentication and redirects can also change the result.

Solution

Inspect the existing configuration before changing it:

  • health_uri: Confirm the endpoint’s documented behavior.
  • health_port: Confirm the check reaches the intended listener.
  • Expected response: Check status requirements and redirect behavior.
  • Passive checks: Inspect any failure window and thresholds already configured.

Use the official health-check reference for your build. Reproduce the check’s safe request conditions from Caddy’s context.

Verification

Confirm the check returns its configured expected result. Then check normal traffic.

Don’t add retries or remove authentication to conceal a failed check.

12. Problem: Intermittent resets or uploads return 502

Symptoms

  • Most requests succeed.
  • Logs include connection reset by peer or EOF.
  • Failures correlate with uploads, restarts, or idle periods.

Cause

Possible causes include application restarts, request-processing faults, and incompatible connection reuse behavior.

Solution

  • Record the exact request time and Caddy build.
  • Match failures with application restarts or worker exits.
  • Compare the upstream’s documented keep-alive timeout with Caddy’s transport configuration.
  • Record the request method, body size, and protocol where available.
  • Review official release notes for a matching issue and affected version.

A release note mentioning uploads doesn’t establish that it fixes your failure. Match the build and reproduction conditions before scheduling an upgrade.

Verification

Use an approved test request or disposable data to reproduce the original conditions. Check application state before retrying a request that may already have been processed.

A 502 doesn’t prove a write failed. Duplicate work is an unpleasant diagnostic result.

Error Messages Table

Exact wording varies by operating system and build.

Error fragmentMeaningFirst check
connect: connection refusedThe connection was rejectedListener, binding address, and destination port
no such hostName resolution failedService name and Caddy-side resolver context
i/o timeoutAn operation exceeded its deadlineWhether it occurred during connection or later I/O
TLS handshake timeoutTLS negotiation didn’t finishProtocol, TLS service, and network path
certificate signed by unknown authorityThe verifier doesn’t trust the issuerUpstream chain and Caddy trust configuration
Certificate name mismatchCertificate identity doesn’t match the expected nameUpstream name and tls_server_name
server gave HTTP response to HTTPS clientThe destination responded with HTTP during an HTTPS attemptUpstream scheme and listener
connection reset by peerThe peer or an intermediary reset the connectionApplication logs and connection reuse
EOFThe stream ended before the expected exchange finishedApplication lifecycle and request details

Platform-Specific Checks

13. Linux: Identify the executable, listener, and logs

For a native deployment, get the confirmed serving process ID from your service or process supervisor:

read -r -p "Confirmed serving Caddy process ID: " caddy_pid
ps -p "$caddy_pid" -o pid=,user=,args=
readlink "/proc/$caddy_pid/exe"

Expected result: process arguments and an executable path linked to that process. Permissions can restrict access.

Run the version command through that executable path:

read -r -p "Confirmed absolute Caddy executable path: " caddy_bin
"$caddy_bin" version

Expected result: the selected executable’s version information. If it was replaced after startup, check deployment records before treating it as the running build.

For confirmed systemd deployments, enter the actual unit name:

read -r -p "Confirmed systemd unit name: " caddy_unit
systemctl show "$caddy_unit" -p ExecStart -p ExecReload -p FragmentPath

# Restrict the log window to the recent failure.
journalctl -u "$caddy_unit" --since "10 minutes ago" --no-pager

Expected result: unit configuration and recent journal entries, subject to permissions. Compare ExecStart and ExecReload with the intended configuration source.

Runtime logs and HTTP access logs are different. Access logging must be configured before you can rely on its output.

Illustrative Caddy executable, active upstream and timestamped runtime error examples

14. Windows: Identify the process and application listener

For a native Windows deployment, inspect the confirmed process ID in PowerShell:

$CaddyProcessId = [int](Read-Host "Confirmed serving Caddy process ID")

Get-CimInstance Win32_Process -Filter "ProcessId = $CaddyProcessId" |
    Select-Object ProcessId, ExecutablePath, CommandLine

Expected result: the selected process’s path and command line. Access to some fields can require an elevated session.

Use the confirmed executable:

$CaddyBinary = Read-Host "Confirmed absolute Caddy executable path"
& $CaddyBinary version

Expected result: version information for the selected executable.

Inspect the upstream port on the Windows machine where the application runs:

$UpstreamPort = [int](Read-Host "Confirmed application TCP port")

Get-NetTCPConnection -State Listen -LocalPort $UpstreamPort |
    Select-Object LocalAddress, LocalPort, OwningProcess

Expected result: listening address, port, and owning process. If there’s no matching listener, check the application and destination.

For a safe probe from a matching Windows network context:

$UpstreamUrl = Read-Host "Exact upstream URL for a documented safe endpoint"

# Use curl.exe explicitly and cap the whole request at 10 seconds.
curl.exe --connect-timeout 5 --max-time 10 --silent --show-error --output NUL --write-out "HTTP %{http_code}\n" "$UpstreamUrl"

Read the results using the same rules as the Linux probe.

Windows log locations depend on how Caddy starts. Inspect the confirmed service wrapper, supervisor, or console-output configuration. Don’t assume runtime logs appear in Event Viewer.

If Caddy runs in a container, host PowerShell checks describe the host. Repeat connectivity checks in the confirmed container context.

Illustrative PowerShell Caddy process, listener and bounded HTTP probe examples

Configuration Issues and Controlled Changes

15. Correct one evidenced setting

These examples belong inside the existing site block. They aren’t complete replacement configurations.

# Within the confirmed source Caddyfile's site block.
# Use loopback only when Caddy and the application share that context.
reverse_proxy 127.0.0.1:8000
# Within the confirmed source Caddyfile's site block.
# Use a service name only after confirming resolution and network membership.
reverse_proxy app:8000

Keep these mistakes separate:

MistakeCorrection
Editing an unused fileIdentify the loaded configuration and its owner
Targeting the wrong portMatch the application’s actual listener
Using container loopback for another serviceUse the verified private destination
Selecting HTTPS for an HTTP listenerMatch the upstream’s actual protocol
Confusing TLS identity with HTTP HostCheck each setting separately
Editing generated configuration directlyChange the authoritative source

Save the original file and deployment metadata before editing. For API-managed deployments, save a protected configuration snapshot and use the existing management workflow.

16. Validate with the matching build and environment

For a confirmed file-based Caddyfile deployment on Linux:

read -r -p "Confirmed absolute Caddy executable path: " caddy_bin
read -r -p "Confirmed absolute Caddyfile path: " caddy_config

caddy_backup="${caddy_config}.before-502-$(date -u +%Y%m%dT%H%M%SZ)"
cp -p -- "$caddy_config" "$caddy_backup"
printf 'Backup: %s\n' "$caddy_backup"

Expected result: a copy of the file and a Backup: line with its path.

Edit one setting supported by the evidence. Then validate:

"$caddy_bin" validate --config "$caddy_config" --adapter caddyfile

For the same native Windows workflow:

$CaddyBinary = Read-Host "Confirmed absolute Caddy executable path"
$CaddyConfig = Read-Host "Confirmed absolute Caddyfile path"

$CaddyBackup = "$CaddyConfig.before-502-$([DateTime]::UtcNow.ToString('yyyyMMddTHHmmssZ'))"
Copy-Item -LiteralPath $CaddyConfig -Destination $CaddyBackup
Write-Output "Backup: $CaddyBackup"

Expected result: a copy of the file and a Backup: line with its path.

After editing:

& $CaddyBinary validate --config $CaddyConfig --adapter caddyfile

Expected result: validation completes successfully, without configuration errors. Resolve errors before reloading.

These examples apply to Caddyfiles. The --adapter caddyfile flag selects that format. JSON and other adapters need the matching command.

Validation can load or provision modules. Run it with the required files, permissions, environment, and modules available. It doesn’t prove upstream connectivity.

17. Reload through the confirmed deployment mechanism

For systemd, use this only after confirming ExecReload loads the intended candidate:

read -r -p "Confirmed systemd unit name with a verified reload action: " caddy_unit
sudo systemctl reload "$caddy_unit"

Then inspect the runtime logs for the reload result.

For Windows, containers, and other supervisors, use the existing verified reload procedure. Confirm it targets the serving instance and intended configuration source.

Don’t assume a successful file edit changed the running route.

If verification fails, restore the saved configuration, validate it, and apply the same controlled reload. For an image upgrade, retain the previous image identity and configuration.

Prevention Tips

  • Record the upstream’s binding address, internal port, and protocol beside the deployment configuration.
  • Keep configuration ownership clear across files, APIs, and deployment tools.
  • Save executable versions or image digests with each deployment.
  • Keep clocks aligned so you can match proxy and application logs.
  • Document a safe diagnostic endpoint with its expected response.
  • Review keep-alive and health-check settings when application behavior changes.
  • Keep configuration backups outside public web roots.

A UPS can reduce abrupt shutdowns in a homelab, but it won’t correct an upstream port mismatch. Keep hardware resilience and routing diagnosis separate.

Verify the Result and Escalate Safely

18. Verify the original failing request

Repeat the original request only when it’s safe. For a write or upload, first establish whether the application already processed it.

Confirm:

  • The expected public response arrives.
  • Caddy logs show no matching upstream transport failure.
  • Application logs show the intended request and result.
  • The active route contains the intended correction.
  • Rollback remains available.

One successful request supports that request’s path. For intermittent failures, watch the workload and conditions that previously triggered them.

19. Escalate with a redacted evidence bundle

Collect:

  • Exact Caddy version and executable or image identity.
  • Linux or Windows version and deployment method.
  • A small topology description.
  • The active configuration source and minimal relevant route.
  • The upstream listener’s address, port, and network context.
  • Probe command, context, timestamp, and result.
  • Matching Caddy and application log excerpts.
  • Recent changes and safe reproduction conditions.
  • The proposed correction, validation result, and rollback status.

Redact authorization headers, cookies, credentials, tokens, sensitive query strings, and application data. Replace private names consistently so the topology remains clear.

Use the Caddy community forum for troubleshooting discussion. Use the official GitHub repository for a reproducible software defect, following its issue guidance.

Wrapping Up

Match the listener, active route, and network context before changing settings. I’d favor one proven correction over a bundle of timeout and retry changes. It’s easier to verify and undo.

StepActionApplies To
IdentifyRecord the serving build and active configurationEvery deployment
InspectMatch the upstream to its actual listenerConnectivity failures
ProbeTest safely from Caddy’s network contextLinux, Windows, and containers
CorrectChange one evidenced setting and validateConfiguration failures
VerifyCheck the original request and matching logsEvery correction
EscalateShare a redacted evidence bundleUnresolved failures

Keep the last working configuration and reload procedure together. That small habit makes the next repair repeatable.