Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 79

Serverless AI Deployment

This lesson is built with resources from medium.com.

Hello! Welcome to the fifth lesson in our final module, Deploying AI Models as Services.

In the last lesson, you successfully containerized your secure, streaming AI application using Docker. You now have a portable, self-contained Docker image named ai-streaming-api:latest on your local machine. This is the professional standard for packaging applications, but its true power is unlocked when you deploy it to the cloud.

This lesson is the culmination of our deployment journey. Your learning outcome is to deploy a containerized AI application to a serverless platform. We'll take your local Docker image and make it a publicly accessible, scalable web service using Google Cloud Run. Your background as a backend engineer and your experience with Docker will be highly valuable here, as we'll be focusing on the specific commands and cloud-native workflow for deploying AI services.

1. Why Serverless Containers?

For modern AI applications, especially those built for variable or unpredictable usage, a serverless container platform like Google Cloud Run or AWS App Runner is an excellent choice. Here's why:

  • Zero Infrastructure Management: You provide a container image, and the platform handles the rest—provisioning, networking, and scaling. You don't manage any servers.
  • Automatic Scaling (including to zero): The service automatically scales the number of running containers based on incoming traffic. Crucially, it can scale down to zero when there are no requests, meaning you pay nothing for idle time. This is perfect for development, personal projects, and applications with intermittent traffic.
  • Pay-per-use: You are billed only for the CPU and memory your container consumes while it's processing requests.

Our goal is to follow a standard cloud deployment pattern: push our container image to a private registry and then deploy it from that registry to the serverless environment.


2. The Deployment Workflow with Google Cloud Run

We'll use Google Cloud Run for this lesson. The overall process consists of three main stages:

  1. Push the Image to a Registry: We can't deploy an image that only exists on our local machine. We need to push it to a central, cloud-based container registry. We'll use Google Artifact Registry, which is tightly integrated with other Google Cloud services.
  2. Deploy to Cloud Run: We will instruct Cloud Run to pull our image from the Artifact Registry and run it as a managed service.
  3. Configure and Verify: We'll configure the running service with the necessary environment variables (our API key) and verify that the public endpoint is working correctly.

3. Step-by-Step Deployment Guide

Let's walk through the process. Make sure you have the Google Cloud SDK installed and have authenticated by running gcloud auth login. You will also need a Google Cloud project with billing enabled.

Step 1: Prepare Your Google Cloud Environment

First, we need to enable the APIs for Artifact Registry and Cloud Run. Set your project ID and a preferred region in your terminal for convenience.

# Replace YOUR_PROJECT_ID with your actual GCP project ID
export PROJECT_ID=$(gcloud config get-value project)
export REGION=us-central1 # You can choose another region if you prefer

# Enable the necessary services
gcloud services enable artifactregistry.googleapis.com run.googleapis.com

Step 2: Push Your Docker Image to Artifact Registry

A registry is a repository for storing and managing your container images. Let's create one and push our image to it.

The following guide provides a clear walkthrough of this process. We will adapt its commands for our ai-streaming-api image.

Deploying Docker Containers to Google Cloud Run

The article 'Deploying Docker Containers to Google Cloud Run' by Akaash Hazarika provides a great production-ready guide for this process. We'll focus on the steps for setting up Artifact Registry and pushing an image.

Read 'Step 2: Build and Push to Artifact Registry'. Focus on the three sub-steps: 'Create a Repository', 'Build and Tag the Image', and 'Push the Image'. We will execute these commands next.

Now, let's execute those steps:

  1. Create an Artifact Registry repository: This is a one-time setup per project. We'll name our repository ai-apps.

    gcloud artifacts repositories create ai-apps \
      --repository-format=docker \
      --location=$REGION \
      --description="Docker repository for AI applications"
    
  2. Authenticate Docker: This command configures your local Docker client to authenticate with your new Artifact Registry repository.

    gcloud auth configure-docker ${REGION}-docker.pkg.dev
    
  3. Tag and Push your image: Your local image (ai-streaming-api:latest) needs to be tagged with the full path of the registry you just created. Then you can push it.

    # Define the full image name with the registry path
    export IMAGE_NAME=${REGION}-docker.pkg.dev/${PROJECT_ID}/ai-apps/ai-streaming-api:v1
    
    # Tag your local image with the new name
    docker tag ai-streaming-api:latest $IMAGE_NAME
    
    # Push the tagged image to Artifact Registry
    docker push $IMAGE_NAME
    

Your container image is now stored securely in Google Cloud, ready for deployment!

Step 3: Deploy the Container to Cloud Run

With the image in the registry, deploying it is a single command. We will use gcloud run deploy. This is where we also securely provide our API_KEY.

The most important aspect of deploying an application with secrets is ensuring those secrets are not hardcoded or stored in the container image. In the previous lesson, we used --env-file for local runs. For Cloud Run, we will use the --set-env-vars flag to inject the key as an environment variable into the running container.

The following resource shows the basic deployment command.

Deploying Docker Containers to Google Cloud Run

Let's refer back to 'Deploying Docker Containers to Google Cloud Run' for the deployment command structure.

Review 'Step 3: Deploy to Google Cloud Run'. Pay close attention to the gcloud run deploy command and its flags, especially --image and --allow-unauthenticated.

Now, let's construct the full command for our service. Replace YOUR_HUGGINGFACE_API_KEY with your actual key.

gcloud run deploy ai-streaming-service \
  --image=$IMAGE_NAME \
  --region=$REGION \
  --platform=managed \
  --allow-unauthenticated \
  --set-env-vars="API_KEY=YOUR_HUGGINGFACE_API_KEY"

Let's break down the flags:

  • ai-streaming-service: The name we're giving our new service.
  • --image=$IMAGE_NAME: Tells Cloud Run which image to pull from Artifact Registry.
  • --allow-unauthenticated: Makes the service publicly accessible. For production, you would typically secure this with IAM.
  • --set-env-vars="API_KEY=...": This securely injects the API key into the runtime environment of your container. For production, you should use a dedicated secret manager like Google Secret Manager, but this method is fine for our learning purposes.

After running the command, gcloud will prompt you for a few confirmations and then deploy your service. This may take a few minutes. When it's done, it will print the public Service URL.

Step 4: Verify Your Deployment

Now for the final test. Use curl to hit the public URL provided by Cloud Run. Make sure to use the same API key you configured for the service.

# Get your service URL from the deployment output or Cloud Console
export SERVICE_URL="YOUR_CLOUD_RUN_SERVICE_URL"

# Use the same API key you used in the previous lesson for authentication
export CLIENT_API_KEY="my-super-secret-ai-api-key"

curl -N -H "X-API-Key: $CLIENT_API_KEY" "$SERVICE_URL/query-stream/?query=What+is+serverless+computing"

If everything is set up correctly, you should see a streaming response from the LLM, served live from your globally-accessible, serverless API!

If you encounter errors, you can view the logs for your service by navigating to the Cloud Run section of the Google Cloud Console and selecting your ai-streaming-service. The logs there are invaluable for debugging.

Test your understanding!

Your service currently scales to zero, which is great for cost savings. However, this can lead to a "cold start" delay for the first request after a period of inactivity. How would you modify the gcloud run deploy command to ensure at least one container is always running to prevent this? (Hint: The article on deploying a GenAI app mentions this).

Show answer

You would add the --min-instances=1 flag to your gcloud run deploy command. This tells Cloud Run to always keep at least one container instance running and ready to serve requests, which eliminates cold start latency at the cost of paying for an idle instance. The full command might look like this: gcloud run deploy ai-streaming-service ... --min-instances=1.


Conclusion

Fantastic work! You have successfully completed the full lifecycle of a modern AI application: from local code to a containerized image, and finally to a scalable, serverless deployment in the cloud. This workflow is a cornerstone of MLOps and professional AI engineering.

Key Takeaways:

  • Serverless container platforms like Google Cloud Run abstract away infrastructure management and provide cost-effective, automatic scaling.
  • The standard deployment workflow involves pushing a Docker image to a container registry (like Google Artifact Registry) and then deploying it from there.
  • The gcloud CLI is a powerful tool for managing the entire deployment process, from creating repositories to deploying and configuring services.
  • Secrets should never be in your container image. They must be injected at runtime using environment variables or a secret management service.

What's Next?
Your service is live, but how do you know if it's healthy and performing well? In our next and final lesson, you will learn to implement structured logging to capture requests, predictions, and errors for monitoring. This is the final piece of the puzzle for operating a production-grade AI service.