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:
And to configure a bit:
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)
And run the build artifact on Google Cloud Run.
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:
Then add the TXT entry shown to your DNS configuration. Additionally a CNAME for the domain to use, for example:
DNS may take a few minutes for the verification and CNAME registration to propagate. When this has happenend register the domain mapping:
Now the FastAPI minimal api is running at https://hello.madflex.de until I delete the Google Cloud Run service for it. 🙂