A Detailed Guide to Configuring a Serverless FastAPI Application in GCP
In this article, we’ll explore how to configure a FastAPI application in a serverless environment using Google Cloud Platform (GCP). This guide will take you through all the necessary steps, from application development to deployment using Cloud Run.
1. Prerequisites
Before starting, ensure you have the following:
2. Why Serverless with Cloud Run?
Google Cloud Run is a managed serverless platform that allows you to deploy containerized applications. With Cloud Run, you benefit from:
3. Setting Up a FastAPI Application
Start by creating a basic FastAPI application.
Create a project folder:
mkdir fastapi-cloud-run
cd fastapi-cloud-run
Set up a virtual environment:
python3 -m venv venv
source venv/bin/activate
Install FastAPI and Uvicorn:
pip install fastapi uvicorn
Write the application code:
Create a file named main.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, GCP Cloud Run with FastAPI!"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
Test locally:
Run the application locally to ensure it works:
uvicorn main:app --host 0.0.0.0 --port 8000
Visit https://127.0.0.1:8000 in your browser.
Containerizing the FastAPI Application
Cloud Run uses Docker containers, so we need to containerize the application.
Create a Dockerfile:
# Use the official Python image as a base
FROM python:3.10-slim
# Set the working directory in the container
WORKDIR /app
# Copy the application files
COPY ./requirements.txt /app/requirements.txt
COPY ./main.py /app/main.py
# Install the dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Expose the port FastAPI will run on
EXPOSE 8000
# Command to run the application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Create a requirements.txt:
fastapi
uvicorn
Build the Docker image:
docker build -t fastapi-cloud-run .
Test the container locally:
docker run -p 8000:8000 fastapi-cloud-run
Verify it works by visiting https://127.0.0.1:8000.
Deploying to GCP Cloud Run
Push the Docker image to Google Container Registry (GCR):
Authenticate Docker with GCP:
gcloud auth configure-docker
Tag the Docker image:
docker tag fastapi-cloud-run gcr.io/<PROJECT-ID>/fastapi-cloud-run
Push the image to GCR:
docker push gcr.io/<PROJECT-ID>/fastapi-cloud-run
Deploy the container to Cloud Run:
gcloud run deploy fastapi-cloud-run \
--image gcr.io/<PROJECT-ID>/fastapi-cloud-run \
--platform managed \
--region us-central1 \
--allow-unauthenticated
Replace <PROJECT-ID> with your GCP project ID.
Access your deployed application:
After deployment, you’ll receive a public URL. Use it to access your FastAPI application.
Configuring Environment Variables
To manage sensitive information like database credentials, you can configure environment variables:
Set environment variables in Cloud Run:
gcloud run services update fastapi-cloud-run \
--update-env-vars DATABASE_URL="your-database-url"
Access these variables in your FastAPI app:
import os
database_url = os.getenv("DATABASE_URL")
Setting Up HTTPS
Cloud Run automatically provisions HTTPS for your application. No additional configuration is required.
8. Logging and Monitoring
To monitor your application:
gcloud logging read "resource.type=cloud_run_revision" --limit 100
9. Cleanup
To avoid unnecessary charges, delete the resources when they are no longer needed:
gcloud run services delete fastapi-cloud-run
gcloud container images delete gcr.io/<PROJECT-ID>/fastapi-cloud-run
Conclusion
Deploying a serverless FastAPI application on GCP Cloud Run is a seamless way to build and scale applications without worrying about infrastructure. This setup is ideal for stateless microservices, APIs, or web applications. By leveraging Cloud Run's managed environment, you can focus on your application code while GCP handles scaling, security, and networking.
Thank you for taking the time to read! Follow me for more insights and updates, and let’s continue to grow and learn together.