Kudos https://medium.com/coinmonks/blockchain-development-environment-775176fd88f3

How to use cloud_sql_proxy on docker-compose

Adilson Carvalho
Adilson's Notes
Published in
2 min readSep 13, 2018

--

When using Google's Cloud SQL you'll have to use their proxy to reach your database instances as they're not expose publically by default (what is great!).

For most usages, you just download the proxy binary and use it as explained on their documentation. It's easy and reliable.

For those using docker-compose, they can use it locally on their development environment in a very similar way it's used on Kubernetes.

They provide a handy image and that image could be used on your docker-compose file:

Creating the cloud-sql-proxy service

It's no different from creating any other service on a docker-compose.yml file.

Use a base image, configure the command applying your specific values for PROJECTID, ZONE, INSTANCE and database PORT.

What about credentials?

We need credentials to access the instance through the proxy and to keep it simple (and secure), to share credentials must be avoided as much as start creating them for each developer that need to work with your project.

So lets use the default credentials issued by gcloud to each user. This would be achievable by mounting our credential on a volume named /credential and on the command pass it as the-credential_file=/credential option.

Sweet, isn't. But there is a gotcha 😔

The gotcha is when you try to use your application_default_credentials that is at ~/.config/gcloud/application_default_credentials.json. It will be rejected because it is an authorized_user one and it is expected a service_account one.

Error when trying to use the developer's credential instead of a service object.

The way that works

When you use the cloud_sql_proxy locally it works just fine, so there is a way. I found that the best is to just mount our credentials directory inside the container and then cloud_sql_proxy will handle it just like it does on our local machine.

To achieve that we simply mount our credentials directory inside the container using ~/.config:/root/.config. I totally undertand that this usage has some concerns, but it sounds handy enough to use.

Consuming the cloud-sql-proxy service

Now we have a database instance

To reach your database, you'll use cloud-sql-proxy as your host on your configurations, using the default port for your database, 3306 for MySQL and 5433 for PostgreSQL.

On the example above I've used a connection url suitable for sequelize.

All the rest, usernames, passwords, etc are exactly the ones you got from your DBA.

Important to say that this credential use method also is good when needed to deal with all Google Cloud services like PubSub, Datastore, BigQuery, and so on.

--

--

Adilson Carvalho
Adilson's Notes

Curious developer, founder member of GURU-PR, fountain pen addict, husband, father.