Introducing a new way to review your PRs.

Read the announcement

hcavarsan / kftray

kubectl port-forward manager and reverse tunnel (ngrok-like) for exposing local services publicly, with TLS termination, HTTP traffic inspection, UDP forwarding, multi-hop proxy routing through k8s clusters, stateful config via filesystem or git - GUI and TUI available

View on GitHub

19 documents · Updated Nov 23, 2026

docs / kubernetes-port-forwarding

Kubernetes port forwarding

Kubernetes port forwarding turns a saved connection target into a local TCP or UDP endpoint. It resolves the target through the Kubernetes API, keeps a local listener tied to the selected workload, and manages local resources and cluster resources as one connection lifecycle. The Kubernetes API path can also use supported HTTP or SOCKS proxy routes. This page is a child of Connection forwarding; compare SSH forwarding for the SSH path and Endpoint exposure and TLS for public endpoint behavior.

Forwarding model

Target selection

The forwarder accepts a namespace, a target selector, and a remote port. A service target becomes the service's pod label selector. A pod target uses its label selector directly. A named remote port is resolved against the selected ready pod so a rollout can change the number behind the name without sending traffic to a stale port. The mapping stays tied to the pod that supplied it and is cleared when that pod changes or a connection fails.

References: crates/…/models.rs• L110-154 crates/…/target.rs• L25-59 crates/…/listener.rs• L632-728

The same target model supports direct workload forwarding and relay-backed forwarding. UDP and proxy-style routes use a relay pod created for the configuration. A plain TCP service or pod route connects to the selected workload.

References: crates/…/models.rs• L110-154 crates/…/start.rs• L1138-1162

Local data paths

The local listener is the client-facing side of the tunnel. Each TCP client gets a connection worker and a Kubernetes port-forward stream. A shared limit bounds open upstream streams across TCP and UDP, so a busy forward applies back-pressure instead of creating unlimited cluster connections. The two TCP streams copy bytes in both directions until a client, the upstream, or cancellation ends the connection. UDP keeps a session per local peer and gives each peer its own upstream tunnel so replies return to the correct client.

TCP can add a local TLS boundary when the configuration enables SSL. HTTP logging can be enabled or disabled while a connection is open. When enabled, it tracks bounded HTTP request and response data until a WebSocket upgrade. The tunnel then switches to opaque byte forwarding without dropping bytes from the upgrade read. UDP uses bounded admission and retires failed or idle peer sessions instead of keeping unlimited state.

References: crates/…/listener.rs• L159-172 crates/…/listener.rs• L732-925 crates/…/listener.rs• L1200-1235 crates/…/tcp_forwarder.rs• L26-29 crates/…/tcp_forwarder.rs• L325-481 crates/…/tcp_forwarder.rs• L485-855 crates/…/tcp_forwarder.rs• L952-1033

Kubernetes client boundary

The Kubernetes client boundary resolves the selected context and kubeconfig into a client and a canonical cluster identity. The identity ties setup, forwarding, and cleanup to the same API server. A cached client can be reused, but a changed kubeconfig or a changed destination must not silently redirect an existing forward.

When a proxy is configured, the client routes API traffic through an HTTP or HTTPS proxy or through SOCKS5 or SOCKS5H. The client keeps the selected TLS mode while it builds that route. It rejects unsupported proxy schemes before forwarding starts and applies proxy credentials only through the proxy protocol that supports them.

References: crates/…/mod.rs• L24-79 crates/…/shared_client.rs• L45-66 crates/…/proxy.rs• L18-62 crates/…/proxy.rs• L64-187

Startup lifecycle

Startup stages

Startup prepares local resources before it opens the Kubernetes stream. It then resolves the target, waits for a usable pod, binds the local endpoint, and registers the running process only after all owned resources are known. Registration stores a configuration snapshot so a later stop can clean up what this run actually used, even if the saved configuration changes.

The lifecycle follows this order:

  1. Claim or allocate the local address and claim host-file ownership.
  2. Resolve the Kubernetes target and create the port-forward client.
  3. Probe the selected pod and open the local TCP or UDP listener.
  4. Write any requested host alias.
  5. Persist the running snapshot and register the process.
  6. Start the optional forward timeout.

The startup token can cancel work after the relay is ready and before registration. Every early exit rolls back the local resources and records anything that still needs cleanup.

References: crates/…/start.rs• L903-1054 crates/…/start.rs• L1056-1120 crates/…/start.rs• L1123-1240

Running state

Each active forward has one process owner with a cancellation token, listener task, upstream forwarder, connection workers, and background watchers such as HTTP log state sync. The process registry is the source used by stop and status flows to find active work. A configuration lock prevents two starts or a start and stop from crossing the registration boundary.

The listener closes worker registration before shutdown drains workers. A connection accepted at the same time is either added to the drain or aborted. This keeps every accepted connection tied to a tracked owner.

The forward is considered running only after its snapshot and state row are saved. If that state write fails, the listener is stopped and startup cleanup runs instead of leaving an untracked local endpoint.

References: crates/…/port_forward.rs• L35-48 crates/…/listener.rs• L197-202 crates/…/listener.rs• L960-972 crates/…/start.rs• L1056-1108 crates/…/start.rs• L1329-1415

Shutdown lifecycle

Shutdown first cancels the listener and its workers, then waits for them within a bound. The listener also stops its HTTP log watcher and background tasks before it shuts down the Kubernetes forwarder. It releases local ownership after the forwarder stops. A timeout is reported as incomplete because an aborted task can still hold a socket until it is polled again.

The stop path treats cleanup as two separate obligations:

  • Cluster resources, such as relay resources, are removed from the recorded cluster.
  • Local resources, such as loopback aliases and host entries, are removed from the machine.

Each obligation stays recorded until its own removal is confirmed. This prevents a successful local cleanup from hiding a cluster resource, or the reverse.

References: crates/…/listener.rs• L1090-1158 crates/…/port_forward.rs• L118-180 crates/…/stop.rs• L58-117 crates/…/stop.rs• L1201-1287

Local endpoint allocation

Local port selection

The configured local port is used when it is non-zero. Port zero asks the operating system to choose a free port. Before contacting Kubernetes, the forwarder checks whether the requested TCP or UDP port is already in use or cannot be bound. A bind failure can include a free-port suggestion that callers can offer to the user.

TCP and UDP use separate operating-system socket checks. A free port is only a candidate at check time, so the real listener bind remains the final authority.

References: crates/…/local_port.rs• L23-51 crates/…/local_port.rs• L109-137 crates/…/port_forward.rs• L386-449

Loopback address allocation

The local address defaults to 127.0.0.1. A configuration can request a custom loopback address or an automatically allocated address. Automatic allocation first asks the helper to reserve an address for the service identity. If that path is not available, the forwarder scans the custom loopback range and verifies each candidate before use.

An address claim protects the chosen alias while startup is in progress. The stop path will not remove an address held by another active forward or by a newer startup attempt. The chosen address is saved only when it still belongs to the requesting configuration.

References: crates/…/start.rs• L398-484 crates/…/start.rs• L692-763 crates/…/start.rs• L792-854

Host-file integration

Domain aliases

When a configuration enables a domain alias, the alias points to the address where the local listener runs. The host-file manager can write through the privileged helper or use a direct writer. It tracks ownership and verifies removal so a shared alias is not removed while another active configuration still needs it.

Host-file work is claimed before the write. This lets an abandoned startup distinguish its own deferred write from a newer attempt for the same configuration. Failed writes remain cleanup obligations when a line may still exist.

References: crates/…/start.rs• L995-1054 crates/…/hostsfile.rs• L19-45 crates/…/hostsfile.rs• L184-196

HTTPS aliases

When local SSL is active for a TCP forward, the system can add the configured alias and its .local form for HTTPS use. These entries have separate ownership records because SSL may be enabled at start time without being visible in the base connection configuration. The records survive a process restart until matching lines are verified on disk and removed.

References: crates/…/start.rs• L126-175 crates/…/hostsfile.rs• L116-181 crates/…/hostsfile.rs• L812-857

Network access

Loopback configuration

Custom loopback addresses may need an interface alias before a listener can bind. The network utilities first use the helper, then use a platform-specific path when supported, and finally verify that the address is accessible. The default loopback addresses need no setup.

Removal follows the same ownership idea. A missing alias is success, a temporary removal fault remains retryable, and a missing privilege path is reported as a user-action issue rather than retried forever.

References: crates/…/network_utils.rs• L30-119 crates/…/network_utils.rs• L231-387

Privileged local binds

On Unix, ports below 1024 on a loopback address may require elevated access. The listener first tries a normal bind. If the operating system denies that bind and the address and port match the supported privileged case, the helper performs the bind and returns the socket to the application. The requested address must match the socket the helper created.

The preflight check reports likely needs for hosts-file access, loopback setup, and privileged ports before a batch starts. It does not prompt or change the machine. Endpoint exposure and TLS does not use these local resources in the same way because its public path is cluster-backed.

References: crates/…/privileged_bind.rs• L25-117 crates/…/privileges.rs• L29-83 crates/…/privileges.rs• L86-155

Error and recovery behavior

Startup errors

Startup errors identify the stage that failed and distinguish local setup from Kubernetes access. Service lookup errors distinguish a missing service from forbidden access or an unavailable API server. Pod readiness and port-forward upgrade failures include the useful cluster cause, such as missing pods/portforward permission. Proxy setup errors identify an unsupported proxy scheme or a failure to build the selected client route.

Startup probes resolve the target, wait for a ready pod, and open a first stream under bounded time. A timeout names the stage that ran out of time and can include why selected pods are not ready. A timeout does not prove that a cluster create did not happen, so uncertain cluster work remains recorded for later reconciliation.

References: crates/…/target.rs• L62-70 crates/…/proxy.rs• L18-62 crates/…/proxy.rs• L64-139 crates/…/listener.rs• L267-437 crates/…/port_forward_error.rs• L4-35

Live connection failures

A failed upstream stream closes the affected local connection and records the latest connection error for the configuration. A later successful connection clears that error without allowing an older completion to overwrite a newer result. Repeated stream failures or a dead pod can signal recovery.

The shared stream budget treats a ten-second wait for capacity as back-pressure. It closes the affected client without treating load as proof that the relay is broken. Other stream-open failures count toward recovery, and five consecutive failures signal recovery. A pod-death event signals recovery at once. UDP uses the same upstream budget and reports failed sessions through the same recovery path.

TCP accepts new clients with bounded backoff after listener errors. After ten consecutive accept errors, the listener stops. UDP drops packets when its session, queue, or upstream budgets are full. Failed UDP sessions use a short cooldown so an unreachable relay is not retried for every datagram.

References: crates/…/listener.rs• L242-264 crates/…/listener.rs• L777-925 crates/…/listener.rs• L1161-1235 crates/…/tcp_forwarder.rs• L384-481 crates/…/tcp_forwarder.rs• L601-855 crates/…/udp_forwarder.rs• L402-451

Cleanup recovery

Cleanup records preserve the configuration snapshot and the cluster destination that may still own resources. A later stop or reconciliation pass can retry unresolved work after a restart. Cleanup refuses to act on a different API server when the saved destination no longer matches the current context.

Cluster creation with an unknown result stays uncertain until repeated checks confirm that the resource is absent. Resource deletion uses ownership and identity checks so a replacement object with the same name is not deleted by an old cleanup attempt.

References: crates/…/stop.rs• L203-317 crates/…/stop.rs• L367-484 crates/…/stop.rs• L1245-1265

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep target selection, named-port resolution, and pod readiness aligned. A rollout can change the pod or the number behind a named port between startup and the first client.
  • Keep the local resource claims aligned with stop cleanup. Address allocation and host-file writes can finish after a startup task is cancelled.
  • Keep the canonical cluster identity the same for setup, process registration, and cleanup. A changed kubeconfig must not make cleanup act on a different cluster.
  • Keep proxy scheme handling aligned with all Kubernetes TLS client paths. A supported proxy must preserve the selected TLS mode and credential rules.
  • Keep TCP and UDP bind diagnostics aligned with privileged bind behavior. A helper-aware error must not label an available privileged bind as a port conflict.
  • Keep host-file ownership records aligned with alias cleanup. Unmarked legacy lines and SSL aliases need enough history to be attributed without removing another forward's entry.
  • Keep the open-stream budget and recovery signals distinct. Capacity pressure must not trigger relay recovery, while repeated stream-open failures and pod death must remain visible to recovery.
  • Keep HTTP log state and stream mode aligned. A WebSocket upgrade must stop HTTP parsing without dropping bytes that belong to the tunnel.
  • Keep listener worker registration closed under the same boundary as worker draining. A connection accepted during shutdown must not become untracked.

Important failure modes

TriggerConsequenceGuard
The selected service has no usable selectorThe forward cannot identify target podsReject empty or selectorless service targets before building the pod selector
A named port is read from a pod that is replaced during startupTraffic may use the wrong port number or fail to openTie the port number to pod identity and resolve again after churn
A requested local port is busy or deniedKubernetes work would fail after local setup has already startedCheck the local bind before cluster contact and keep the real bind as the final check
A startup is cancelled during address or host-file workAn alias or address can outlive the startup taskUse startup claims and durable local cleanup records
The current kubeconfig resolves to a different API serverCleanup could report success while old cluster resources keep runningCompare the recorded and current canonical cluster identities
A proxy scheme is unsupported or a proxy client route cannot be builtKubernetes API access fails before target resolutionValidate the scheme and report the client-construction error
A helper or privilege path is unavailable during cleanupLocal aliases or host entries can remainSeparate retryable failures from privilege-unavailable outcomes and surface both clearly
Open streams consume the shared budgetNew clients are closed after the capacity wait instead of being admittedTreat permit timeout as back-pressure and keep the permit for the full stream lifetime
A WebSocket upgrade is split across reads or shares a read with its first frameHTTP logging can corrupt the tunnel boundary or log frame bytes as HTTPDetect the complete handshake before switching modes and forward the original bytes unchanged
Shutdown races with a new TCP acceptA worker can remain alive without an owner to stop itClose worker registration under the same lock used to drain workers

Key files

FileWhy to read it
crates/…/start.rsMain Kubernetes forward startup, local resource claims, registration, and cancellation path
crates/…/listener.rsTCP and UDP listener ownership, target-port refresh, stream admission, connection errors, recovery signals, and shutdown
crates/…/tcp_forwarder.rsTCP byte flow, optional TLS handoff, live HTTP logging, and WebSocket mode changes
crates/…/proxy.rsKubernetes API routes through HTTP, HTTPS, and SOCKS proxy types across TLS modes
crates/…/target.rsService and pod selector resolution plus named-port handling
crates/…/models.rsShared target, port, namespace, and forward concepts
crates/…/stop.rsLocal and cluster cleanup ownership, retry records, and destination checks
crates/…/port_forward.rsPer-forward process ownership and bounded shutdown behavior
crates/…/local_port.rsLocal TCP and UDP port checks and user-facing bind diagnostics
crates/…/network_utils.rsCustom loopback setup and release across supported platforms
crates/…/privileged_bind.rsHelper-backed binding for privileged loopback ports
crates/…/hostsfile.rsHost-file write, ownership, verification, and cleanup behavior
crates/…/privileges.rsPreflight view of local resources that may need elevation