'kubectl - determine local port used when port-forwarding on random local port?

kubectl lets one port forward to a remote service like so

$ kubectl port-forward service/my-service :12345 

How can I find out the local port that was chosen, and used by kubectl in this command?

Additional details: I'd like to be able to determine this from a script, that looks for an active port forward for a service. If a port forward isn't found, it creates a port forward on a free local port, and returns the port number (which is what the above does)



Solution 1:[1]

When you use the $ kubectl port-forward service/my-service :12345 command, you must get an output like this:

Forwarding from 127.0.0.1:XXXX -> YYYY
Forwarding from [::1]:XXXX -> YYYY

And that’s the only way you have to identify the local chosen port, you can add to your script an instruction to read that value form the output. The XXXX number is the number of the local chosen port. I can suggest you to use service type Nodeport instead of port-forward. Using NodePort, you are able to expose your app as a service and have access from outside the Kubernetes. Take a look into the following documentation for more examples.

Solution 2:[2]

This(bash function) may not be a cleaner way but works on a kubeadm cluster. Tried with multiple forwarding same time for different pods/svc.

get_local_port()
{
port="${1}"
if [ -z "${port}" ];then
    echo "[Error]: 1st argument should be the remote port number"
    return 1
fi
netstat -plnt |\
awk -vpid="$(ps -eaf |awk -v port=${port} '{if(match($0,"port-forward.*"port)) printf "%s|", $2}'|sed -r 's/.$//g')" '{if(match($NF,"^"pid"/")) {split($4,a,":");print a[2]}}'

}

Usage:

get_local_port <remote-port-number>

Explanation:

This command is parsing the ps -eaf to get the PID of the port-forwarding command and later parses it over netstat to get the local port.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nestor Daniel Ortega Perez
Solution 2 P....