Building a FastAPI-Powered Number Classification API on Mac & GCP
Deploying an application on Google Cloud Platform (GCP) using a Mac can be a rewarding experience, but it comes with its challenges. In this blog post, I will walk you through the steps taken to deploy my app successfully, including the commands used, scripts written, challenges faced on Mac and GCP Linux, and solutions. By the end, you will be equipped with the knowledge to deploy your own application.
First, you need a GCP account. If you haven't set one up, go to Google Cloud Console and create a new project.
Next, enable the necessary APIs and services:
# Enable required APIs
gcloud services enable compute.googleapis.com
gcloud services enable iam.googleapis.com
gcloud services enable sqladmin.googleapis.com
gcloud services enable cloudbuild.googleapis.com
On Mac, install the GCP SDK using Homebrew:
brew install --cask google-cloud-sdk
Then, initialize the gcloud CLI:
gcloud init
Follow the prompts to authenticate and set the default project.
Set the default compute region and zone:
gcloud config set compute/region us-central1
gcloud config set compute/zone us-central1-a
To host the app, create a Compute Engine VM instance:
gcloud compute instances create my-app-instance \
--machine-type=e2-medium \
--image-family=debian-11 \
--image-project=debian-cloud \
--boot-disk-size=20GB \
--tags=http-server,https-server
Allow HTTP and HTTPS traffic:
gcloud compute firewall-rules create allow-http \
--allow=tcp:80 \
--target-tags=http-server
SSH into the VM:
gcloud compute ssh my-app-instance
Install dependencies:
sudo apt update && sudo apt install -y git python3-pip nginx
Clone your app repository:
git clone https://github.com/your-repo/your-app.git
cd your-app
Install Python dependencies:
pip3 install -r requirements.txt
Run the application:
python3 main.py
If using a web server like Flask, start it on a public IP:
flask run --host=0.0.0.0 --port=5000
To attach a domain, set up a static IP:
gcloud compute addresses create my-app-ip --region=us-central1
Retrieve the assigned IP:
gcloud compute addresses list
Update your domain’s DNS settings to point to this IP.
For HTTPS, install Certbot:
sudo apt install certbot python3-certbot-nginx
Then, generate an SSL certificate:
sudo certbot --nginx
Homebrew sometimes fails due to permission errors. Running:
sudo chown -R $(whoami) /usr/local/*
helped resolve this.
Even after allowing HTTP traffic, the app was not accessible. Running:
gcloud compute firewall-rules list
showed that the firewall rule was missing, so I added it manually.
Some files lacked execution permissions. Running:
chmod +x your_script.sh
fixed this issue.
Deploying an app on GCP using a Mac requires setting up the CLI, creating a VM, installing dependencies, and configuring firewall rules. Despite challenges with Mac’s permissions and GCP's networking, solutions exist. I hope this guide helps you deploy your own application seamlessly. Happy coding!