Browse topics

kubectl port-forward

Version
1.37
Review
Draft

Summary#

kubectl port-forward opens a local TCP listener and forwards connections to a port on one Pod. You can name the Pod directly or let kubectl select one from a workload or Service.

Syntax#

sh
kubectl port-forward pod/POD 18080:8080
kubectl port-forward service/SERVICE 18080:80
kubectl port-forward pod/POD :8080

With a Service, specify its port; kubectl forwards to the corresponding target port on a selected Pod. An empty local port makes kubectl choose a free one.

Example#

The script starts an HTTP server in a Pod and fetches its response through a loopback-only forward. It needs curl locally.

sh
(
  set -eu
  ns="ref-forward-$$"
  work=$(mktemp -d)
  pid=
  created=
  cleanup() {
    if [ -n "$pid" ]; then
      kill "$pid" 2>/dev/null || true
      wait "$pid" 2>/dev/null || true
    fi
    rm -rf -- "$work"
    if [ -n "$created" ]; then kubectl delete namespace "$ns" >/dev/null; fi
  }
  trap cleanup EXIT

  kubectl create namespace "$ns" >/dev/null
  created=yes
  kubectl wait -n "$ns" --for=create serviceaccount/default --timeout=60s >/dev/null
  kubectl apply -n "$ns" -f - <<'YAML'
apiVersion: v1
kind: Pod
metadata:
  name: status
spec:
  terminationGracePeriodSeconds: 1
  containers:
    - name: web
      image: busybox:1.37
      command: ["sh", "-ec", "mkdir /www; echo 'status: ready' > /www/index.html; exec httpd -f -p 8080 -h /www"]
      readinessProbe:
        tcpSocket:
          port: 8080
        periodSeconds: 1
YAML
  kubectl wait -n "$ns" --for=condition=Ready pod/status --timeout=120s >/dev/null
  kubectl port-forward -n "$ns" --address=127.0.0.1 pod/status :8080 >"$work/forward.log" 2>&1 &
  pid=$!
  tries=0
  until port=$(sed -n 's/^Forwarding from 127\.0\.0\.1:\([0-9][0-9]*\) -> 8080$/\1/p' "$work/forward.log") && [ -n "$port" ]; do
    tries=$((tries + 1)); [ "$tries" -lt 20 ] && kill -0 "$pid" 2>/dev/null || { cat "$work/forward.log" >&2; exit 1; }
    sleep 1
  done
  curl --noproxy '*' -fsS --max-time 5 "http://127.0.0.1:$port/"
)

Expected output#

Text
pod/status created
status: ready

Common mistakes#

The forward ends if the selected Pod terminates, even when a Deployment replaces it. Start a new session in that case. Keep the listener on loopback for local debugging; binding to 0.0.0.0 lets other hosts reach it if your network permits.

Version applicability#

The example targets Kubernetes 1.37. kubectl is supported within one minor version of the API server.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0