Home  >  Q&A  >  body text

GKE: How to disconnect from a pod after port forwarding through bastion host

<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>
P粉775723722P粉775723722418 days ago509

reply all(1)I'll reply

  • P粉092778585

    P粉0927785852023-08-30 11:59:53

    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

    reply
    0
  • Cancelreply