Solution:
Root Cause: Container Loopback Interface (127.0.0.1) Isolation
When
cloudflared runs inside its own Docker container and ingress rules are configured with
service: http://127.0.0.1:8080, the connector attempts to open a TCP socket on its own isolated container loopback interface rather than reaching the host system or adjacent application containers. Because no process is listening on port 8080 inside the
cloudflared container, the kernel returns an
ECONNREFUSED TCP packet, triggering an HTTP 502 Bad Gateway response at the Cloudflare Edge.
# Diagnostic Verification:
Review
cloudflared container logs using Docker CLI:
bash
docker logs cloudflared 2>&1 | grep -i "connection refused"
Observe log entries similar to:
ERR Request failed error="Unable to reach the origin service. The service may be down or it may not be responding to the receive worker: dial tcp 127.0.0.1:8080: connect: connection refused"
Confirm socket connectivity from inside the container:
bash
docker exec -it cloudflared nc -zv 127.0.0.1 8080
# Step-by-Step Fix:
1. Option A: Use Shared Docker Network Bridge (Recommended):
Join both cloudflared and your application container to the same user-defined bridge network: bash
docker network create tunnel_net
docker network connect tunnel_net cloudflared
docker network connect tunnel_net app_container
Update your ingress service definition in config.yml or Cloudflare Zero Trust Dashboard to reference the container name instead of loopback: yaml
ingress:
- hostname: app.yourdomain.com
service: http://app_container:8080
- service: http_status:404
2. Option B: Reference Host Gateway via
host.docker.internal:
If the application runs directly on the host system outside Docker, pass --add-host to container startup: bash
docker run -d --name cloudflared --add-host=host.docker.internal:host-gateway cloudflare/cloudflared:latest tunnel run
Set ingress target in configuration: yaml
service: [http://host.docker.internal:8080](http://host.docker.internal:8080)
3. Option C: Use Host Network Driver:
Run container with --net=host if running on Linux: bash
docker run -d --name cloudflared --net=host cloudflare/cloudflared:latest tunnel run --token <TOKEN>
# Prevention & Long-Term Monitoring:
Standardize multi-container deployments using docker-compose.yml with explicit service references.Validate tunnel configurations according to official Cloudflare Tunnel Documentation.