π Part 1: Preparing Your FastAPI + Scikit-Learn App for Deployment on Google Cloud Run
π§ Why FastAPI + Scikit-Learn + Google Cloud?
FastAPI gives us a blazing-fast way to expose machine learning models as APIs. With Google Cloud Run, we can deploy those APIs without managing servers, scaling automatically based on traffic.
In this guide, we walk through converting a local machine learning API into a production-ready cloud service β and it all begins with structuring your project.
ποΈ Project Structure
Make sure your folder (we named it ChurnAPI_test) contains the following files:
cssCopyEditChurnAPI_test/
βββ main.py
βββ model.joblib
βββ requirements.txt
βββ Dockerfile
π§Ύ Step 1: Preparing main.py for Cloud Run
The main.py file is the heart of your FastAPI app. Here's a sample version adapted for Google Cloud Run:
pythonCopyEditimport uvicorn
import os
from fastapi import FastAPI
from pydantic import BaseModel
import joblib
import pandas as pd
app = FastAPI()
# Load the model
model = joblib.load("model.joblib")
# Define input schema
class Customer(BaseModel):
data: dict
@app.post("/predict")
def predict(customer: Customer):
try:
df = pd.DataFrame([customer.data])
prediction = model.predict(df)[0]
probability = model.predict_proba(df)[0][1]
return {
"prediction": int(prediction),
"churn_probability": round(probability, 3)
}
except Exception as e:
return {"error": str(e)}
# β
Cloud Run entry point
if __name__ == "__main__":
port = int(os.environ.get("PORT", 8080))
uvicorn.run("main:app", host="0.0.0.0", port=port)
π Key differences from local testing is we include this part of code:
if name == "__main__":
port = int(os.environ.get("PORT", 8080))
uvicorn.run("main:app", host="0.0.0.0", port=port)
Uses
host="0.0.0.0"(required by Docker)Reads
PORTfrom environment variable (used by Cloud Run)No
reload=True(thatβs only for local development)
π Step 2: Create requirements.txt
Google Cloud needs to know which Python packages to install inside your Docker container. Thatβs where requirements.txt comes in.
β Steps to Create It:
In your project folder (
ChurnAPI_test), create a new text file.Rename the file exactly to:
fastapi
uvicorn
pandas
joblib
scikit-learn
π Add any extra libraries your model or code depends on (e.g., numpy, xgboost).
π³ Step 3: Create Dockerfile
Docker lets us package our app, model, and dependencies into a portable container. Hereβs the Dockerfile for our project:
β
How to Create a Dockerfile (Step-by-Step)
π In your ChurnAPI_test project folder:
Open Notepad or any plain text editor.
Paste the following code (this is the full working version):
# Use official Python image
FROM python:3.10-slim
# Set working directory inside the container
WORKDIR /app
# Copy all files from your local folder into the container
COPY . .
# Install required Python packages
RUN pip install --no-cache-dir -r requirements.txt
# Expose port Cloud Run will use
ENV PORT 8080
EXPOSE 8080
# Start FastAPI app with uvicorn
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]
π³ Full Dockerfile Explained (Line-by-Line)
This Dockerfile tells Google Cloud how to build and run your FastAPI + scikit-learn app inside a container. Below is the complete version with clear explanations for each step:
# β
Step 1: Start with a lightweight official Python 3.10 image
FROM python:3.10-slim
This pulls a minimal version of Python 3.10 as the base. The
slimvariant keeps the image small and fast, which is ideal for cloud deployments.
# β
Step 2: Set the working directory inside the container
WORKDIR /app
This creates a directory called
/appinside the container and sets it as the working directory. All subsequent commands will run from here.
# β
Step 3: Copy all project files into the container
COPY . .
This copies everything from your local project folder (
ChurnAPI_test) into the/appdirectory inside the container. That includesmain.py,model.joblib,requirements.txt, and your Dockerfile itself.
# β
Step 4: Install the Python dependencies listed in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
This installs all the required Python packages inside the container.
- The
--no-cache-dirflag helps reduce the final image size.
# β
Step 5: Set the environment variable for the port (used by Cloud Run)
ENV PORT 8080
EXPOSE 8080
Google Cloud Run sends requests to your app through port 8080.
ENV PORT 8080sets the environment variable.
EXPOSE 8080tells Docker this is the port your app will listen on.
# β
Step 6: Start the FastAPI server using Uvicorn
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]
This is the command Docker runs when your container starts.
It launches your FastAPI app usinguvicorn, making it accessible publicly.
main:appβmain.pyfile andapp = FastAPI()--host 0.0.0.0β ensures the app listens to external traffic (not just localhost)--port 8080β matches the port Cloud Run will send traffic to
β Summary
This Dockerfile:
Sets up a clean Python environment
Installs your machine learning app's dependencies
Starts your FastAPI app correctly for production
Once built, this container can be deployed to any cloud platform, including Google Cloud Run, with no code changes.
π Part 2: Setting Up Google Cloud SDK and CLI for FastAPI Deployment
In Part 1, we built a FastAPI app with a scikit-learn model, added a Dockerfile, and got everything ready for deployment. In this post, weβll walk through how to set up Google Cloud CLI (gcloud) and prepare your environment to deploy that app to the cloud.
Letβs get started!
π§© Step 1: Install the Google Cloud SDK
Google Cloud CLI is a command-line tool used to deploy, manage, and monitor services on Google Cloud.
π Download and Install:
π https://cloud.google.com/sdk/docs/install
β Follow the instructions for your operating system (Windows/macOS/Linux). After installing, open Command Prompt (or Terminal) and check if it's working:
gcloud --version
You should see the version number and some installed components.
π Step 2: Authenticate with Google Cloud
To link your terminal with your Google Cloud account, run:
gcloud auth login
This will:
Open a browser window
Ask you to log in to your Google account
Authenticate your terminal session with Google Cloud
ποΈ Step 3: Set Your Google Cloud Project
You must tell gcloud which project you're working on. Based on your dashboard, your Project ID is:
churnapi-456817
Run:
gcloud config set project churnapi-456817
β This ensures all future commands (like build and deploy) apply to your churn project.
βοΈ Step 4: Enable Required Google Cloud Services
By default, services like Cloud Run and Cloud Build are not enabled. These must be turned on manually:
gcloud services enable run.googleapis.com
gcloud services enable cloudbuild.googleapis.com
π‘ Why?
| Service | Why It's Needed |
run.googleapis.com | Hosts your FastAPI container on Google Cloud Run |
cloudbuild.googleapis.com | Builds your Docker image from your folder |
Once enabled, you're ready to build and deploy π
π§ Confirm Everything Is Set
You can confirm your project and services are configured by running:
gcloud config list
You should see:
[core]
project = churnapi-456817
And you're ready for deployment!
π Part 3: Deploying Your FastAPI + Scikit-Learn App to Google Cloud Run
In Part 1, we prepared your FastAPI app and Dockerfile. In Part 2, we set up Google Cloud SDK and enabled required services. Now, in Part 3, weβll build the container and deploy it to the cloud!
Letβs put your API into production.
ποΈ Step 1: Build and Submit Your Docker Image to Google Cloud
Make sure you're in your project folder that contains:
main.py
Dockerfile
requirements.txt
model.joblib
Then run this in your terminal:
cd C:\Users\nickolat\Desktop\ChurnAPI_test
Now build and upload your Docker image using Cloud Build:
gcloud builds submit --tag gcr.io/churnapi-456817/churn-api
π What this does:
Uses your
Dockerfileto build an imageTags it as
churn-apiUploads it to your Google Container Registry
Once it finishes, you'll see:
DONE
IMAGE: gcr.io/churnapi-456817/churn-api
β Youβve now got a ready-to-deploy container!
π Step 2: Deploy to Google Cloud Run
Now deploy your container to Cloud Run using this command:
gcloud run deploy churn-api \
--image gcr.io/churnapi-456817/churn-api \
--platform managed \
--region asia-south1 \
--allow-unauthenticated
π‘ Explanation:
| Option | What it does |
churn-api | The name of your service |
--image | Points to your built Docker image |
--platform managed | Uses the fully managed Cloud Run platform |
--region asia-south1 | Deploys to the Mumbai region |
--allow-unauthenticated | Makes your API publicly accessible |
Youβll then see output like:
Service [churn-api] revision [churn-api-00001-xzy] has been deployed.
Service URL: https://churn-api-1069019972109.asia-south1.run.app
β This is your live API URL!
π Step 3: Test Your API on the Web
Visit the Swagger UI:
π https://churn-api-1069019972109.asia-south1.run.app/docs
Youβll see an interactive interface where you can test the /predict endpoint.
π Sample JSON to Use:
jsonCopyEdit{
"data": {
"Online Security": "No",
"Online Backup": "Yes",
"Device Protection": "Yes",
"Tech Support": "No",
"Contract": "Month-to-month",
"Paperless Billing": "Yes",
"Payment Method": "Electronic check",
"Married": "No",
"Offer": "None",
"Premium Tech Support": "No",
"Unlimited Data": "Yes",
"Internet Info": "Fiber Optic",
"Revenue Category": "2000β5000",
"Total Charges Category": "200β400",
"Monthly Charge Category": "70β90",
"Total Long Distance Charge Category": "0β20",
"Avg Monthly GB Download Category": "20β40",
"Age Category": "26β35",
"Dependents_Category": "No",
"Referrals_Category": "1β2",
"Tenure_Category": "6β12 months"
}
}
Hit βExecuteβ and youβll get a prediction result and churn probability!
β Final Thoughts
Youβve now:
Packaged your machine learning model
Deployed it with FastAPI inside a Docker container
Made it publicly accessible on Google Cloud Run
Your churn prediction API is now production-ready and can be called from anywhere β including your .NET frontend, mobile apps, or third-party tools.