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, deploy it to a
Google Kubernetes Engine (GKE) Autopilot
cluster, and configure Identity and Access Management (IAM) permissions with
Workload Identity Federation for GKE.
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. kubectlandgke-gcloud-auth-plugininstalled. For instructions, see Installkubectl.- Swift 6.2 or later installed locally. For setup instructions, see Quickstart: Get started with Swift.
- Permissions to create clusters and manage resources, such as the Kubernetes
Engine Admin (
roles/container.admin), Cloud Build Editor (roles/cloudbuild.builds.editor), Artifact Registry Administrator (roles/artifactregistry.admin), and Project IAM Admin (roles/resourcemanager.projectIamAdmin) IAM roles. The required APIs enabled in your project:
gcloud services enable \ aiplatform.googleapis.com \ artifactregistry.googleapis.com \ cloudbuild.googleapis.com \ cloudresourcemanager.googleapis.com \ container.googleapis.com \ iam.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 GKEGemini cd GKEGemini swift package init --name GKEGemini --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 GKEGemini \ --package swift-google-cloud-aiplatform-v1 swift package add-target-dependency \ Hummingbird GKEGemini --package hummingbird
Write the HTTP service
On GKE, the client library automatically authenticates using
Application Default
Credentials through the
GKE metadata server provided by
Workload Identity Federation for GKE. Replace the contents of
Sources/GKEGemini/GKEGemini.swift by following these steps:
Import the required modules:
Define the application entry point:
Read the
GOOGLE_CLOUD_PROJECT,HOST, andPORTenvironment 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 yourGKEGeminidirectory 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/GKEGemini /app/GKEGemini USER swift:swift EXPOSE 8080 ENTRYPOINT ["/app/GKEGemini"]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
GKEGeminibinary 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
Build and push the container image
To build and push the container image to Artifact Registry, follow these steps:
Set your project ID, project number, and region environment variables:
export PROJECT_ID=$(gcloud config get project) export PROJECT_NUMBER=$(gcloud projects describe "${PROJECT_ID}" \ --format="value(projectNumber)") export REGION=us-central1Create an Artifact Registry repository to store the container image:
gcloud artifacts repositories create gke-apps \ --repository-format=docker \ --location="${REGION}" \ --description="Docker repository for GKE 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}/gke-apps/gke-gemini:latest"
Create a cluster and configure IAM
To create a GKE Autopilot cluster and grant permissions using Workload Identity Federation for GKE, follow these steps:
Create a GKE Autopilot cluster, which enables Workload Identity Federation for GKE by default:
gcloud container clusters create-auto gke-gemini-cluster \ --region="${REGION}"Configure
kubectlto communicate with your cluster:gcloud container clusters get-credentials gke-gemini-cluster \ --region="${REGION}"Create a dedicated Kubernetes
ServiceAccountfor your application:kubectl create serviceaccount gke-gemini-ksa --namespace=defaultGrant the Kubernetes
ServiceAccountthe Vertex AI User role (roles/aiplatform.user) so Pods running asgke-gemini-ksacan invoke Gemini models:gcloud projects add-iam-policy-binding "${PROJECT_ID}" \ --role="roles/aiplatform.user" \ --member="principal://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${PROJECT_ID}.svc.id.goog/subject/ns/default/sa/gke-gemini-ksa" \ --condition=NoneFor information about Google Cloud APIs that don't support direct
principal://bindings, see Workload Identity Federation for GKE.
Deploy to GKE
To deploy the service to your GKE cluster, follow these steps:
Create a Kubernetes manifest file named
deployment.yamlthat configures aDeploymentusing thegke-gemini-ksaservice account and aServiceto expose it:cat <<EOF > deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: gke-gemini spec: replicas: 1 selector: matchLabels: app: gke-gemini template: metadata: labels: app: gke-gemini spec: serviceAccountName: gke-gemini-ksa containers: - name: gke-gemini image: ${REGION}-docker.pkg.dev/${PROJECT_ID}/gke-apps/gke-gemini:latest ports: - containerPort: 8080 env: - name: GOOGLE_CLOUD_PROJECT value: "${PROJECT_ID}" resources: requests: cpu: "500m" memory: "512Mi" --- apiVersion: v1 kind: Service metadata: name: gke-gemini-service spec: type: ClusterIP selector: app: gke-gemini ports: - protocol: TCP port: 80 targetPort: 8080 EOFApply the manifest to your cluster and wait for the deployment to become available. GKE Autopilot might take a few minutes to provision compute capacity for the first Pod:
kubectl apply -f deployment.yaml kubectl rollout status deployment/gke-gemini --timeout=5m
Verify the deployed service
To test the deployed service, follow these steps:
Forward a local port to the service running in your GKE cluster:
kubectl port-forward service/gke-gemini-service 8080:80In a separate terminal, send a request to the service:
curl http://localhost:8080/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 workloads, inspect Pod logs, and monitor cluster metrics on the Kubernetes Engine page in the Google Cloud console.
Clean up
To avoid incurring ongoing charges on your Google Cloud account, see GKE pricing, Artifact Registry pricing, Cloud Build pricing, and Vertex AI pricing, and delete the resources you created:
Delete the GKE cluster:
gcloud container clusters delete gke-gemini-cluster \ --region="${REGION}"Delete the Artifact Registry repository:
gcloud artifacts repositories delete gke-apps \ --location="${REGION}"Remove the IAM policy binding:
gcloud projects remove-iam-policy-binding "${PROJECT_ID}" \ --role="roles/aiplatform.user" \ --member="principal://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${PROJECT_ID}.svc.id.goog/subject/ns/default/sa/gke-gemini-ksa" \ --condition=NoneOptional: 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/GKEGemini/GKEGemini.swift:
What's next
- Learn how to deploy a Swift service to Cloud Run.
- 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.