Introduction
This post explains how to deploy a FastAPI app using Google Cloud Run.
Prerequisites
- Google Cloud account
- gcloud CLI
- Docker
- Python
Project setup
Create a FastAPI app using Poetry.
pip install poetry
poetry new sample
cd sample
mv sample app
cd app
poetry add fastapi
poetry add 'uvicorn[standard]'
Create app/main.py
touch app/main.py
Edit main.py as follows
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/", tags=["root"])
async def root():
return {"message": "Hello World"}
Run it in uvicorn
poetry shell
uvicorn app.main:app --reload
Google Cloud Run setup
If you have already installed gcloud CLI, update it as follows.
gcloud components update
Connect the gcloud CLI to your GCP account.
gcloud auth login
Set up your project ID
gcloud config set project PROJECT_ID
Region settings
gcloud config set run/region REGION
Docker settings
gcloud auth configure-docker
Prepare Dockerfile in the same hierarchy as the app directory.
FROM python:3.11.3
ENV PYTHONUNBUFFERED True
RUN pip install --upgrade pip
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
ENV APP_HOME /root
WORKDIR $APP_HOME
COPY /app $APP_HOME/app
EXPOSE 8080
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080"]
Prepare requirements.txt file for Dockerfile.
(In this case, use requirements.txt in the Dockerfile.)
poetry export -f requirements.txt --output requirements.txt
Now that it is ready, deploy to Cloud Run.
gcloud run deploy sample --port 8080 --source .
If successful, it will be created with the name sample.
A URL will be created, so check the operation.
Conclusion
With the above, you can now deploy your FastAPI app to Google Cloud Run.
Although the details are omitted here, it would be a good idea to actually add CORS and headers in middleware and implement an authentication function such as Firebase Authentication.
Note: The path to import must be specified from the app directory.
Example: app/lib/test.py
# app/main.py
from app.lib import test
Top comments (0)