How to deploy a FastAPI Project on Google Cloud Platform!
How to deploy a FastAPI Project on Google Cloud Platform
This tutorial will guide you through the process of creating a FastAPI project from scratch and running it on Google Cloud Platform (GCP) using Artifact Registry and Cloud Run.
Prerequisites
Before starting this tutorial, ensure you have the following:
- A Google Cloud Platform account.
- Google Cloud SDK installed on your local machine.
- Basic knowledge of Docker and FastAPI.
Step 1: Create a FastAPI Project
Follow these steps to create a FastAPI project:
- Create a new directory for your project.
- Inside the project directory, create your FastAPI application according to your requirements (prefeable in a new virtual environment).
Step 2: Set Up Artifact Registry on GCP
- Go to the Google Cloud Platform console.
- Navigate to Artifact Registry.
- Click on “Create Repository” and provide a name for your repository.
- Set the region, format to Docker, and mode to Standard.
- Choose the location region (e.g., asia-southeast1).
- Click “Create”.
Step 3: Configure Docker
- Open the Docker on Google Cloud Platform.
- Click on “Setup instructions”.
- Follow the instructions to configure Docker with Google Cloud Registry, it should show something like that terminal code, copy and paste it in the terminal.
$gcloud auth configure-docker \
asia-southeast1-docker.pkg.dev
Step 4: Build and Push Docker Image
- Open your terminal and navigate to your project directory.
- Run the following commands, replacing placeholders with your actual values:
# Set environment variables
export PATH=$PATH:/Users/mahmoud/Desktop/google-cloud-sdk/bin/
export CLOUDSDK_PYTHON=python3
DOCKER_VERSION=1.0.0
DOCKER_ACCOUNT_NAME=your_docker_account_name
HOST_NAME=asia-southeast1-docker.pkg.dev
PROJECT_ID=your_google_cloud_platform_project_id
REPOSITORY=your_repository_id
IMAGE=your_image_name
# Authenticate Docker with Google Cloud Registry
gcloud auth configure-docker $HOST_NAME
# Build Docker image
docker build -t $DOCKER_ACCOUNT_NAME/$IMAGE:$DOCKER_VERSION .
# Tag Docker image
docker tag $DOCKER_ACCOUNT_NAME/$IMAGE:$DOCKER_VERSION $HOST_NAME/$PROJECT_ID/$REPOSITORY/$IMAGE:$DOCKER_VERSION
# Push Docker image to Google Cloud Registry
docker push $HOST_NAME/$PROJECT_ID/$REPOSITORY/$IMAGE:$DOCKER_VERSION
Step 5: Deploy to Cloud Run
- Verify that the Docker image is successfully pushed to Artifact Registry.
- Go to Cloud Run and click on “Create Service”.
- Select your previously created image.
- Leave all settings as default and click “Create”.
- Ensure the port matches the one specified in your FastAPI application (e.g., 8000).
Conclusion
Congratulations! You have successfully created a FastAPI project from scratch and deployed it on Google Cloud Platform using Artifact Registry and Cloud Run.
Next Steps
You can now continue to develop your FastAPI application and utilize command-line tools for continuous deployment on Google Cloud Platform.