How to front your Google Cloud Run public endpoint with Fastly #fastly #googlecloudrun

Share on:

If you are using Google Cloud Run, then you know that once you deploy your service, Cloud Run automatically provisions and exposes a unique, HTTPS endpoint for your container. This usually comes in the form of https://YOUR-SERVICE-NAME-.a.run.app.The endpoint will remain intact, while you deploy new versions and will change only if you do any destructive operations like undeploy or delete.

So in general it works well and the fact that you don't have to do TLS on your end is a huge benefit. If you don't mind a exposing this endpoint to your clients you are done!

There are cases though that you would like to front this endpoint, do some caching before the request hit's your _origin _ or make routing decisions, validations or checks. Of course you can go the Google route, where you can register a custom domains, make use of Google CDN etc and this is all fine.

I am a huge supporter of Fastly (biased opinion), so I wanted to front one of Google Cloud Run services with Fastly. I already maintan a Domain (through AWS) and I front it with Fastly so the idea was to reusue my personal domain and _hide _ my Cloud Run Application, under a specific path, behind my own domain. Fastly would do the actul request to my origin and of course it could cache my responses.

For example for the domain www.papo.gr I wanted to you hide my cloud run application behind www.papo.gr/api/application . I also, did not want to do a regular redirect on the browser (meaning I did not want to reveal the Google Clour Run endpoint to the browser etc).

It is actually fairly simple to do this in Fastly. I will just provide the details using the Fastly web UI and in a later post I will add the relevant terraform configuration.

Step 1: Add your Cloud Run Endpoint as a backend (Host) on your Fastly Config

We name this Backend (gcloud).

Very important on the Advanced Options, you make sure you populate the _Overide Host _ with the Cloud Run endpoint host.

Step 2: Add VCL (snippet or custom) up to you, to do the _redirect _ based on the url

I have opted, prividing my own custom _Main.vcl _ where I have overriden the _vcl_recv _ function with the rule I want to apply

1sub vcl_recv { 
2 # if you want my blog- redirect to it! 
3 if (req.url ~ "^/api/application(/\[^? )?(\\?. )?$") { 
4 set req.backend = F_gcloud; 
5 } 
6 #FASTLY recv 
7}

Done!