Running CloudSQL Proxy as a Service on Windows using Powershell

Firstly I want to shout out to Doug Mahugh and his article which inspired this one. All I have done is implement his solution in Powershell so I can include it as part of a startup script for immutable VMs.

I won’t cover too much of what Doug covered but will quote his opening paragraph about why we use the proxy:

The Cloud SQL proxy provides fast, secure, encrypted connections to Cloud SQL database instances, without any need to manage allowed IP addresses or SSL/TLS configuration details. It’s a small self-contained executable that you can download for free, and it uses IAM authentication for simple role-based access management. The proxy is great for local development and testing, because once it’s running all your code and client tools can connect to 127.0.0.1 to access your databases instances.

But as the Proxy is only available for Windows as an EXE (if Google is reading this we would love it as an MSI, pretty please!) we have to do some additional work to turn it into an always running service that could survive reboots and the like. For this Doug suggests the use of this favourite service manager NSSM (Non-Sucking Service Manager) to take the EXE and register it as a Windows service.

So without further to do when I combine both these ideas (pulling the executables from a bucket) the Powershell looks like this:

#########################
# INSTALL CLOUDSQL PROXY
#########################
Write-Host "Installing CloudSQL Proxy and NSSM Process"
gsutil cp "gs://$GCP_BUCKET/nssm.exe" "C:\Windows\nssm.exe"
gsutil cp "gs://$GCP_BUCKET/cloud_sql_proxy_x64.exe" "C:\Windows\cloud_sql_proxy_x64.exe"
nssm install cloudsql_proxy C:\Windows\cloud_sql_proxy_x64.exe -instances="$CLOUDSQL_CONNECT=tcp:3306" -ip_address_types=PRIVATE
nssm set cloudsql_proxy Start SERVICE_AUTO_START
nssm start cloudsql_proxy

In the above snippet I am pulling both executables from a bucket defined in the $GCP_BUCKET variable into C:\Windows (this location is chosen as it is a default PATH location on Windows which makes running nssm much easier!)

Then the next command uses nssm to install the proxy as a service simply called ‘cloudsql_proxy’ providing the location of the exe but also providing arguments to the proxy, specifically $CLOUDSQL_CONNECT is the connection string of the database.

Finally we set the service to auto start which ensures it comes up following a reboot and tell it to start right now.

Anyway that is all for today I sincerely hope that is helpful for someone else encountering the same problem.

I am a GCP Platform Engineer based in the UK. Thoughts here are my own and don’t necessarily represent my employer.