'GKE: how to close the connection to a pod after port-forwarding via bastion-host

I am working from my local machine with a database deployed in a pod in kubernetes. To connect to it, first up it is necessary to connect to a bastion host VM.

Basically, it is a double ssh tunnel: port 3306 is mapped to port 3306 of the bastion host VM and then to localhost 3306 port via

gcloud beta compute ssh my-bastion-host --project my-gcp-project --zone us-west1-b --command "kubectl -n mynamespace port-forward app-mysqldb-12345-abcde 3306" -- -L3306:127.0.0.1:3306

However, when I terminate the command the connection between the VM and the mysql pod it's not terminated and I need to do it automatically: first up, in the bastion host,

ps -ef|grep port-forward 

to find the the PROCESS_NUMBER then

echo "kill -9 <PROCESS_NUMBER>

to terminate the connection.

Is there a way to close automatically the connection between the bastion host and the mysql pod when the gcloud beta compute ssh is terminated?



Solution 1:[1]

Try this:

gcloud beta compute ssh my-bastion-host --project my-gcp-project --zone us-west1-b --command "bash -c 'kubectl -n mynamespace port-forward app-mysqldb-12345-abcde 3306'; kill -9 $(pgrep -f port-forward)" -- -L3306:127.0.0.1:3306

Solution 2:[2]

As @Saxon suggested, it is to run kill after the kubectl.. It should be killed first before running another port-forwarding operation.

So,You should perform another kill prior to calling the kubectl so it kills any lingering connection before creating a new port-forward, this will solve the error you are getting:

gcloud beta compute ssh my-bastion-host --project my-gcp-project --zone us-west1-b --command "bash -c 'kill -9 $(pgrep -f port-forward); kubectl -n mynamespace port-forward app-mysqldb-12345-abcde 3306'; kill -9 $(pgrep -f port-forward)" -- -L3306:127.0.0.1:3306

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
Solution 2 Bakul Mitra