kubectl - list all port forwards across all services?

If the question is about listing which ports have been forwarded from a client host to a pod on a Kubernetes cluster...I am not aware of a kubectl / kubectl port-forward command for that.

Ultimately, a kubectl port-forward ends up calling the /api/v1/namespaces/{namespace}/pods/{name}/portforward endpoint and establishes a connection to one of the Kubernetes API servers over the SPDY protocol; the kube-apiserver then proxies the connection to a concrete pod. That seems to be the case for when forwarding port(s) with kubectl port-forward to a concrete pod, pod selected from a deployment, or pod for a particular Kubernetes service.

Given that the kube-apiserver proxies the connection, examining the network connections on the client or server side with something like lsof only shows the port number of the proxy (say, 443 or 8443) for connections to it. On the client side then, using the PID, you can figure out on which port it is listening on - that is the local port that's forwarded.

Also on the client side, just listing all kubectl processes using something like ps -f | grep 'kubectl' | grep 'port-forward' will list all current port forwards established with kubectl port-forward


In addition to Dylan's answer, small adjustment to use with jq.

kubectl get svc -o json | jq '.items[] | {name:.metadata.name, p:.spec.ports[] } | select( .p.nodePort != null ) | "\(.name): localhost:\(.p.nodePort) -> \(.p.port) -> \(.p.targetPort)"'
"web1: localhost:30329 -> 8080 -> 8080"
"web2: localhost:30253 -> 8080 -> 8080"

kubectl get svc --all-namespaces -o go-template='{{range .items}}{{range.spec.ports}}{{if .nodePort}}{{.nodePort}}{{"\n"}}{{end}}{{end}}{{end}}'

Port forwards are listed in the services the above command should loop through all of them and print them out