How Tunnels Work¶
Reverse-proxy tunnels allow services running on your local machine (localhost) to be reachable from anywhere on the public internet, bypassing NATs, CGNATs, and restrictive local firewalls.
This guide explains how reverse tunneling works from first principles. By the end, you will understand how commercial tools like ngrok work under the hood, and how to build a lightweight, open-source ngrok alternative from scratch in pure Go.
Sandbox vs. Private Relays
This walkthrough uses the open LocalTunnel protocol (localtunnel.me) as a zero-setup sandbox so you can run the code immediately without cloud infrastructure. In production, Expose also ships its own private, pure-Go relay server (expose server).
Part 1 — What Is a Tunnel?¶
When you run a web server on localhost:3000, external visitors cannot reach it because your machine sits behind a router using Network Address Translation (NAT) with a private IP.
A reverse proxy tunnel solves this by flipping the connection flow: your local machine initiates an outbound TCP connection to a public relay server. Because stateful firewalls permit outbound traffic and its return packets, this connection stays open and acts as a bidirectional bridge.
+---------------+ +-----------------------+ +--------------+
| Internet User | | Public Relay Server | | Local Client |
| (Web Visitor) | --HTTP-> | (e.g. VPS / Relay) | <--TCP-- | (Expose CLI) | --HTTP-> localhost:3000
+---------------+ +-----------------------+ +--------------+
The Request Lifecycle¶
- Registration: The client contacts the relay server and requests a public endpoint (e.g.,
https://my-app.relay.com). - Control Connection: The client establishes an outbound TCP socket to the relay and keeps it alive.
- Visitor Traffic: An external user sends an HTTP request to
https://my-app.relay.com. - Data Multiplexing: The relay streams raw HTTP bytes down the active TCP connection to your client.
- Local Proxying: Your client dials
localhost:3000, writes the request, reads the local response, and pumps it back to the relay.
Part 2 — Building a Minimal Tunnel Client¶
Let's build a working, standalone tunnel client in Go in under 60 lines of code.
Step 1: Request a Tunnel Endpoint¶
First, ask the relay for an assigned subdomain and dedicated TCP relay port:
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type TunnelInfo struct {
URL string `json:"url"`
Port int `json:"port"`
}
func requestTunnel() (*TunnelInfo, error) {
resp, err := http.Get("https://localtunnel.me/?new")
if err != nil {
return nil, err
}
defer resp.Body.Close()
var info TunnelInfo
if err := json.NewDecoder(resp.Body).Decode(&info); err != nil {
return nil, err
}
return &info, nil
}
Step 2: Establish the TCP Relay Connection¶
Next, open an outbound TCP socket to the relay host on the assigned port:
import "net"
func dialTunnel(info *TunnelInfo) (net.Conn, error) {
address := fmt.Sprintf("localtunnel.me:%d", info.Port)
return net.Dial("tcp", address)
}
Step 3: Bidirectional Socket Proxying¶
When incoming HTTP bytes arrive from the relay, dial the local application and stream data in full-duplex using io.Copy:
import (
"fmt"
"io"
"net"
)
func proxyRequest(tunnelConn net.Conn, localPort int) error {
localConn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", localPort))
if err != nil {
return fmt.Errorf("local server offline: %w", err)
}
defer localConn.Close()
// Dual-direction stream pump: visitor -> local, local -> visitor
done := make(chan error, 2)
go func() { _, err := io.Copy(localConn, tunnelConn); done <- err }()
go func() { _, err := io.Copy(tunnelConn, localConn); done <- err }()
// Return when either stream ends; defer closes sockets and unblocks the sibling routine
return <-done
}
Production Optimization: Zero-Allocation Buffer Pooling
While standard io.Copy is clean for scripts, each call allocates a fresh 32 KB buffer on the heap. Under 10,000 active streams, that produces over 640 MB of memory churn, causing Garbage Collector latency spikes.
In production, Expose replaces this with pool.Copy, recycling 32 KB buffers via sync.Pool to eliminate over 95% of heap allocations and keep latency flat under heavy traffic.
Step 4: Putting It All Together¶
Here is the complete runnable program:
package main
import (
"fmt"
"log"
)
func main() {
localPort := 3000
info, err := requestTunnel()
if err != nil {
log.Fatalf("Failed to register tunnel: %v", err)
}
fmt.Printf("✓ Public URL: %s\n", info.URL)
fmt.Printf("✓ Forwarding to: http://localhost:%d\n", localPort)
for {
conn, err := dialTunnel(info)
if err != nil {
log.Printf("Tunnel connection error: %v", err)
break
}
if err := proxyRequest(conn, localPort); err != nil {
log.Printf("Proxy stream closed: %v", err)
}
conn.Close()
}
}
To test it:
# Terminal 1: Start any local web server
python3 -m http.server 3000
# Terminal 2: Run your tunnel client
go run main.go
(Note: This introductory script processes requests sequentially. In Part 5, we show how production Expose handles concurrent traffic using connection pools.)
Part 3 — The Provider Abstraction Pattern¶
Production systems like Expose (an open-source ngrok alternative) support multiple tunnel relays (LocalTunnel, Cloudflare, private self-hosted servers). We use Go interfaces and context propagation to decouple the transport layer.
The Provider Interface¶
// internal/tunnel/provider.go
package tunnel
import "context"
type Provider interface {
// Connect starts the tunnel for the given local port and returns the public URL
Connect(ctx context.Context, localPort int) (string, error)
// Close terminates the tunnel and cleans up socket descriptors
Close() error
// IsConnected reports whether the tunnel transport is currently alive
IsConnected() bool
// PublicURL returns the public HTTP address assigned by the relay
PublicURL() string
// Name returns the provider identifier (e.g. "localtunnel", "selfhosted", "cloudflare")
Name() string
}
Thread-Safe Service Lifecycle¶
Expose coordinates the active provider inside a Service wrapper synchronized with sync.RWMutex and ready channels:
// internal/tunnel/service.go
package tunnel
import (
"context"
"fmt"
"sync"
)
type Service struct {
provider Provider
ready chan struct{}
mu sync.RWMutex
started bool
}
func NewService(p Provider) *Service {
return &Service{
provider: p,
ready: make(chan struct{}),
}
}
func (s *Service) Start(ctx context.Context, localPort int) error {
s.mu.Lock()
if s.started {
s.mu.Unlock()
return fmt.Errorf("tunnel already started")
}
s.started = true
s.mu.Unlock()
if _, err := s.provider.Connect(ctx, localPort); err != nil {
return err
}
close(s.ready) // Signals CLI and caller routines that the URL is live
return nil
}
func (s *Service) Ready() <-chan struct{} { return s.ready }
func (s *Service) PublicURL() string { return s.provider.PublicURL() }
func (s *Service) Close() error { return s.provider.Close() }
Part 4 — Building the CLI with Cobra¶
Expose uses Cobra to offer clean command ergonomics supporting positional arguments, configuration defaults, and flag overrides:
// internal/cli/tunnel.go
package cli
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/spf13/cobra"
)
func NewTunnelCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "tunnel [port]",
Short: "Expose local server via tunnel",
Args: cobra.MaximumNArgs(1),
RunE: runTunnel,
}
cmd.Flags().IntP("port", "p", 0, "Local port to expose")
cmd.Flags().StringP("provider", "P", "localtunnel", "Provider: localtunnel, cloudflare, selfhosted")
cmd.Flags().StringP("server", "s", "", "Self-hosted server relay (e.g. tunnel.mysite.com:7890)")
cmd.Flags().StringP("subdomain", "d", "", "Request a custom subdomain")
return cmd
}
func runTunnel(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Graceful shutdown on Ctrl+C
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
go func() {
<-sigCh
fmt.Println("\nShutting down tunnel...")
cancel()
}()
port := 3000 // Resolved from args, flags, or .expose.yml
svc := tunnel.NewService(selectedProvider)
go svc.Start(ctx, port)
select {
case <-svc.Ready():
fmt.Printf("✓ Public URL: %s\n", svc.PublicURL())
fmt.Printf("✓ Forwarding to: http://localhost:%d\n", port)
case <-ctx.Done():
return ctx.Err()
}
<-ctx.Done()
return svc.Close()
}
Part 5 — Advanced Tunneling Patterns¶
Production tunnel clients must handle connection drops, traffic spikes, and custom routing. Expose solves these through three core patterns:
1. Pre-Warmed Connection Pooling¶
Dialing a new TCP connection on every incoming request adds 50–150ms of latency. To achieve high throughput, the client maintains a pool of pre-warmed idle TCP sockets ready to serve traffic instantly:
func (lt *LocalTunnel) maintainPool(port int, maxConn int) {
for i := 0; i < maxConn; i++ {
go func() {
for lt.IsConnected() {
conn, err := net.Dial("tcp", fmt.Sprintf("localtunnel.me:%d", port))
if err != nil {
time.Sleep(time.Second)
continue
}
lt.handleTraffic(conn) // Handles request and replenishes socket
}
}()
}
}
2. Native Self-Hosted Relays & Heartbeat Ping-Pong¶
Rather than relying on third-party servers, Expose implements its own pure-Go relay protocol (internal/server):
- JSON Control Channel: The client opens a single persistent TCP socket to the relay (
expose server) and sends a registration request: - Heartbeat Eviction: The client transmits a lightweight
PING\nevery 20 seconds. If a network drop occurs, the server's read deadline (60s) evicts the zombie registration to keep the port clean. - On-Demand Data Sockets: When an external HTTP visitor arrives at the relay, the server signals the client to establish a dedicated data connection for that stream.
3. Subprocess Orchestration (Cloudflare Quick Tunnels)¶
For Cloudflare, Expose supervises the official cloudflared binary as a child process and dynamically parses the generated public URL from stderr:
cmd := exec.CommandContext(ctx, "cloudflared", "tunnel", "--url", fmt.Sprintf("http://localhost:%d", port))
stderr, _ := cmd.StderrPipe()
// Read stderr stream to extract the generated trycloudflare.com URL
Architecture Summary¶
| Layer | Responsibility | Location in Expose |
|---|---|---|
Provider Interface |
Common contract across all tunnel transports | internal/tunnel/provider.go |
Service Wrapper |
Channel synchronization & graceful shutdown | internal/tunnel/service.go |
| Buffer Pool | Recycled 32 KB stream buffers (sync.Pool) for zero-allocation proxying |
internal/pool/buffer.go |
| Self-Hosted Server | Pure-Go relay, subdomain routing, & heartbeat timeouts | internal/server/server.go |
| Self-Hosted Client | JSON control plane, deferred local dial, & custom subdomains | internal/provider/selfhosted.go |
| LocalTunnel Client | Public zero-config TCP socket connection pool | internal/provider/localtunnel.go |
| Cloudflare Client | Subprocess supervisor for cloudflared |
internal/provider/cloudflare.go |
| CLI & Commands | Cobra flags, positional port parsing, & signal traps | internal/cli/ |
Next Steps¶
- Self-Hosted Server Guide: Deploy your own private relay server on a $5/mo VPS.
- Architecture Deep Dive: Explore detailed state machines and concurrency models.
- Contributing Guide: Learn how to implement your own custom tunnel provider.