GKE: How to disconnect from a pod after port forwarding through bastion host
P粉775723722
2023-08-29 18:20:49
<p>I am using a local machine to work with a database in a pod deployed in Kubernetes. To connect to it, you first need to connect to the bastion host VM. </p>
<p>Basically, this is a double SSH tunnel: map port 3306 to the bastion host VM's port 3306, and then through the localhost's 3306 port. </p>
<pre class="brush:php;toolbar:false;">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</pre>
<p>However, when I terminate the command, the connection between the VM and the mysql pod is not terminated, I need to do it automatically: First, execute the following command on the bastion host: </p>
<pre class="brush:php;toolbar:false;">ps -ef|grep port-forward</pre>
<p>Find the process number PROCESS_NUMBER, and then execute the following command: </p>
<pre class="brush:php;toolbar:false;">echo "kill -9 <PROCESS_NUMBER></pre>
<p>Terminate the connection. </p>
<p>Is there a way to automatically close the connection between the bastion host and the mysql pod when terminating <code>gcloud beta compute ssh</code>? </p>
Try this: