Use Google Cloud Run with FastAPI

For a webservice project idea that only should serve an atom feed I tried to find an alternative to use a virtual server. Google Cloud Run seems to be a good alternative. So I clicked a free account and tried it.

The easiest way to use the Google Cloud is by using their sdk. On ArchLinux install the community package. The sdk documentation shows how to do this for other Linux distributions and other operating systems.

First step is to login:

gcloud init

And to configure a bit:

gcloud config set run/platform managed
gcloud config set run/region europe-west4

For cloud run we need a Dockerfile to run the code:

FROM tiangolo/uvicorn-gunicorn:python3.8-slim
RUN pip install --no-cache-dir fastapi
COPY ./app /app

The base Docker container used is https://hub.docker.com/r/tiangolo/uvicorn-gunicorn/. And of course a bit of Python code to with the api. The framework used is FastAPI which similar to Flask, but build on Python 3 concepts. This is placed in an app directory and named main.py:

from fastapi import FastAPI
app = FastAPI()

@app.get("/")
async def hello():
    return {"message": "Hello World"}

Now build the container on the Google Cloud. (Replace <PROJECT_ID> with your Google Cloud project ID)

gcloud builds submit --tag eu.gcr.io/<PROJECT_ID>/helloworld

And run the build artifact on Google Cloud Run.

gcloud run deploy hello1 --image eu.gcr.io/<PROJECT_ID>/helloworld --allow-unauthenticated

The last command returns the URL were the code is deployed with a *.run.app domain. Of course we want to run the code with our own domain. The Google Cloud can handle this even with automatic SSL certificates.

First verify your domain:

gcloud domains verify <DOMAIN>

Then add the TXT entry shown to your DNS configuration. Additionally a CNAME for the domain to use, for example:

CNAME hello.madflex.de.  ghs.googlehosted.com.

DNS may take a few minutes for the verification and CNAME registation to propagate. When this has happenend register the domain mapping:

gcloud beta run domain-mappings create --service hello1 --domain hello.madflex.de

Now the FastAPI minimal api is running at https://hello.madflex.de until I delete the Google Cloud Run service for it. 🙂