This document shows you how to build a containerized HTTP service in Swift
using Hummingbird on GitHub and the
Gemini API in Vertex AI. You package the service with a
multi-stage Dockerfile and deploy it to Cloud Run.
Before you begin
To complete the steps in this document, you need the following:
- A Google Cloud project with billing enabled.
- The Google Cloud CLI (
gcloud) installed and initialized. - Swift 6.2 or later installed locally. For setup instructions, see Quickstart: Get started with Swift.
- Permissions to deploy services and manage service accounts, such as the
Cloud Run Admin (
roles/run.admin), Cloud Build Editor (roles/cloudbuild.builds.editor), Artifact Registry Administrator (roles/artifactregistry.admin), Service Account Admin (roles/iam.serviceAccountAdmin), and Project IAM Admin (roles/resourcemanager.projectIamAdmin) Identity and Access Management (IAM) roles. The required APIs enabled in your project:
gcloud services enable \ aiplatform.googleapis.com \ artifactregistry.googleapis.com \ cloudbuild.googleapis.com \ cloudresourcemanager.googleapis.com \ run.googleapis.com
Create a Swift project
To create a new executable Swift package and add the required dependencies, follow these steps:
Initialize a new executable Swift package:
mkdir CloudRunGemini cd CloudRunGemini swift package init --name CloudRunGemini --type executableOptional: If you develop and build locally on macOS, edit
Package.swiftto specifyplatforms: [.macOS(.v15)]. Linux container builds don't require any platform configuration inPackage.swift.Add the Vertex AI client library and Hummingbird as package dependencies:
swift package add-dependency \ https://github.com/googleapis/swift-google-cloud-aiplatform-v1.git --from 0.6.0 swift package add-dependency \ https://github.com/hummingbird-project/hummingbird.git --from 2.0.0Add the product dependencies to your executable target:
swift package add-target-dependency \ GoogleCloudAIPlatformV1 CloudRunGemini \ --package swift-google-cloud-aiplatform-v1 swift package add-target-dependency \ Hummingbird CloudRunGemini --package hummingbird
Write the HTTP service
On Cloud Run, the client library automatically authenticates
using Application Default
Credentials from the
service's attached service account. Replace the contents of
Sources/CloudRunGemini/CloudRunGemini.swift by following these steps:
Import the required modules:
Define the application entry point:
Read the
GOOGLE_CLOUD_PROJECTenvironment variable (configured during deployment) along with theHOSTandPORTenvironment variables:Initialize the
PredictionServiceClientinstance once at startup so it's shared across incoming requests:Configure a route that sends a prompt to Gemini and returns the generated text:
Start the HTTP server listening on the configured host and port:
Containerize the application
To package the application for container builds, follow these steps:
Create a
Dockerfilein the root of yourCloudRunGeminidirectory with the following multi-stage configuration:FROM swift:6.3-bookworm AS builder WORKDIR /app COPY Package.* ./ RUN swift package resolve COPY . . RUN swift build -c release --static-swift-stdlib FROM debian:bookworm-slim RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ libcurl4 \ && rm -rf /var/lib/apt/lists/* RUN useradd --user-group --create-home --system --skel /dev/null \ --home-dir /app swift WORKDIR /app COPY --from=builder /app/.build/release/CloudRunGemini /app/CloudRunGemini USER swift:swift EXPOSE 8080 ENTRYPOINT ["/app/CloudRunGemini"]This
Dockerfileuses two stages to keep the final container image small:- Builder stage: uses the
swift:6.3-bookwormimage, copies the package manifest files first to preserve the dependency cache layer during code-only changes, resolves dependencies, and compiles a release binary with a statically linked Swift standard library. - Runtime stage: copies only the compiled
CloudRunGeminibinary into a minimaldebian:bookworm-slimimage withca-certificates,libcurl4, and a non-rootswiftuser, and then setsENTRYPOINTto start the server on port8080.
- Builder stage: uses the
Create a
.dockerignorefile in the same directory to exclude local build artifacts from the build context:.build .git
Grant permissions and deploy to Cloud Run
To build the container image, grant IAM permissions, and deploy the service to Cloud Run, follow these steps:
Set your project ID and region environment variables:
export PROJECT_ID=$(gcloud config get project) export REGION=us-central1Create an Artifact Registry repository to store the container image:
gcloud artifacts repositories create cloud-run-apps \ --repository-format=docker \ --location="${REGION}" \ --description="Docker repository for Cloud Run apps"Build and push the container image using Cloud Build with a high-CPU machine type (
e2-highcpu-32) to speed up Swift compilation:gcloud builds submit \ --machine-type=e2-highcpu-32 \ --tag="${REGION}-docker.pkg.dev/${PROJECT_ID}/cloud-run-apps/cloud-run-gemini"Create a dedicated service account for the Cloud Run service and grant it the Vertex AI User role (
roles/aiplatform.user) so it can invoke Gemini models:gcloud iam service-accounts create cloud-run-gemini \ --display-name="Cloud Run Gemini Service Account" gcloud projects add-iam-policy-binding "${PROJECT_ID}" \ --member="serviceAccount:cloud-run-gemini@${PROJECT_ID}.iam.gserviceaccount.com" \ --role="roles/aiplatform.user" \ --condition=NoneDeploy the container image to Cloud Run. Choose one of the following authentication options:
- Use
--no-allow-unauthenticatedto require IAM authentication (recommended for internal services or when your organization enforces domain-restricted sharing). - Use
--allow-unauthenticatedto allow public access without authentication.
gcloud run deploy cloud-run-gemini \ --image="${REGION}-docker.pkg.dev/${PROJECT_ID}/cloud-run-apps/cloud-run-gemini" \ --region="${REGION}" \ --service-account="cloud-run-gemini@${PROJECT_ID}.iam.gserviceaccount.com" \ --no-allow-unauthenticated \ --set-env-vars="GOOGLE_CLOUD_PROJECT=${PROJECT_ID}"- Use
Verify the deployed service
To test the deployed service, follow these steps:
Retrieve the URL of the deployed Cloud Run service:
SERVICE_URL=$(gcloud run services describe cloud-run-gemini \ --region="${REGION}" \ --format="value(status.url)")Send a request to the service.
If you deployed with
--no-allow-unauthenticated, include an identity token in theAuthorizationheader:curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" \ "${SERVICE_URL}/"If you deployed with
--allow-unauthenticated, call the URL directly:curl "${SERVICE_URL}/"The service sends the prompt to Gemini and returns a response with suggested names for a dried-flower shop, similar to the following:
Here are a few name ideas for a dried flower shop, broken down by vibe: **Earthy & Bohemian** * Everlasting Bloom * Sun & Stem * Wild & Preserved ...
You can also view your deployed service, inspect request logs, and monitor revisions and metrics on the Cloud Run page in the Google Cloud console.
Clean up
To avoid incurring ongoing charges on your Google Cloud account, see Cloud Run pricing, Artifact Registry pricing, Cloud Build pricing, and Vertex AI pricing, and delete the resources you created:
Delete the Cloud Run service:
gcloud run services delete cloud-run-gemini --region="${REGION}"Delete the Artifact Registry repository:
gcloud artifacts repositories delete cloud-run-apps --location="${REGION}"Remove the IAM policy binding from the service account:
gcloud projects remove-iam-policy-binding "${PROJECT_ID}" \ --member="serviceAccount:cloud-run-gemini@${PROJECT_ID}.iam.gserviceaccount.com" \ --role="roles/aiplatform.user" \ --condition=NoneDelete the service account:
gcloud iam service-accounts delete \ "cloud-run-gemini@${PROJECT_ID}.iam.gserviceaccount.com"Optional: If you created a project specifically for this guide, in the Google Cloud console, go to the Manage resources page and delete the project:
Complete code
The following example shows the complete code for
Sources/CloudRunGemini/CloudRunGemini.swift:
What's next
- Learn how to generate text using the Gemini API in Vertex AI.
- Learn how to override the default authentication credentials.
- Learn how to enable debug logging to troubleshoot requests and responses.
- Browse the Google Cloud client libraries for Swift reference documentation.