Deploy a Swift service to GKE

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.
  • kubectl and gke-gcloud-auth-plugin installed. For instructions, see Install kubectl.
  • 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:

  1. Initialize a new executable Swift package:

    mkdir GKEGemini
    cd GKEGemini
    swift package init --name GKEGemini --type executable
    
  2. Optional: If you develop and build locally on macOS, edit Package.swift to specify platforms: [.macOS(.v15)]. Linux container builds don't require any platform configuration in Package.swift.

  3. 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.0
    
  4. Add 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:

  1. Import the required modules:

    import Foundation
    import GoogleCloudAIPlatformV1
    import Hummingbird

  2. Define the application entry point:

    @main
    struct GKEGemini {
      static func main() async throws {

  3. Read the GOOGLE_CLOUD_PROJECT, HOST, and PORT environment variables:

    let env = ProcessInfo.processInfo.environment
    guard let projectId = env["GOOGLE_CLOUD_PROJECT"], !projectId.isEmpty else {
      fatalError("GOOGLE_CLOUD_PROJECT environment variable is required")
    }
    let host = env["HOST"] ?? "0.0.0.0"
    let port = env["PORT"].flatMap(Int.init) ?? 8080

  4. Initialize the PredictionServiceClient instance once at startup so it's shared across incoming requests:

    let client = try PredictionServiceClient()
    let model = "projects/\(projectId)/locations/global/publishers/google/models/gemini-2.5-flash"

  5. Configure a route that sends a prompt to Gemini and returns the generated text:

    let router = Router()
    router.get("/") { _, _ -> String in
      let request = GenerateContentRequest().with {
        $0.model = model
        $0.contents = [
          Content().with { content in
            content.role = "user"
            content.parts = [
              Part().with { part in
                part.data = .text(
                  "What's a good name for a flower shop that specializes in selling bouquets of dried flowers?"
                )
              }
            ]
          }
        ]
      }
      let response = try await client.generateContent(request: request)
      if case .text(let text) = response.candidates.first?.content?.parts.first?.data {
        return text
      }
      return "No response generated.\n"
    }

  6. Start the HTTP server listening on the configured host and port:

        let app = Application(
          router: router,
          configuration: .init(address: .hostname(host, port: port))
        )
        try await app.runService()
      }
    }

Containerize the application

To package the application for container builds, follow these steps:

  1. Create a Dockerfile in the root of your GKEGemini directory 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 Dockerfile uses two stages to keep the final container image small:

    • Builder stage: uses the swift:6.3-bookworm image, 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 GKEGemini binary into a minimal debian:bookworm-slim image with ca-certificates, libcurl4, and a non-root swift user, and then sets ENTRYPOINT to start the server on port 8080.
  2. Create a .dockerignore file 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:

  1. 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-central1
    
  2. Create 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"
    
  3. 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:

  1. Create a GKE Autopilot cluster, which enables Workload Identity Federation for GKE by default:

    gcloud container clusters create-auto gke-gemini-cluster \
        --region="${REGION}"
    
  2. Configure kubectl to communicate with your cluster:

    gcloud container clusters get-credentials gke-gemini-cluster \
        --region="${REGION}"
    
  3. Create a dedicated Kubernetes ServiceAccount for your application:

    kubectl create serviceaccount gke-gemini-ksa --namespace=default
    
  4. Grant the Kubernetes ServiceAccount the Vertex AI User role (roles/aiplatform.user) so Pods running as gke-gemini-ksa can 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}./subject/ns/default/sa/gke-gemini-ksa" \
        --condition=None
    

    For 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:

  1. Create a Kubernetes manifest file named deployment.yaml that configures a Deployment using the gke-gemini-ksa service account and a Service to 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
    EOF
    
  2. Apply 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:

  1. Forward a local port to the service running in your GKE cluster:

    kubectl port-forward service/gke-gemini-service 8080:80
    
  2. In 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:

  1. Delete the GKE cluster:

    gcloud container clusters delete gke-gemini-cluster \
        --region="${REGION}"
    
  2. Delete the Artifact Registry repository:

    gcloud artifacts repositories delete gke-apps \
        --location="${REGION}"
    
  3. 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}./subject/ns/default/sa/gke-gemini-ksa" \
        --condition=None
    
  4. 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:

    Go to Manage resources

Complete code

The following example shows the complete code for Sources/GKEGemini/GKEGemini.swift:

import Foundation
import GoogleCloudAIPlatformV1
import Hummingbird

@main
struct GKEGemini {
  static func main() async throws {
    let env = ProcessInfo.processInfo.environment
    guard let projectId = env["GOOGLE_CLOUD_PROJECT"], !projectId.isEmpty else {
      fatalError("GOOGLE_CLOUD_PROJECT environment variable is required")
    }
    let host = env["HOST"] ?? "0.0.0.0"
    let port = env["PORT"].flatMap(Int.init) ?? 8080

    let client = try PredictionServiceClient()
    let model = "projects/\(projectId)/locations/global/publishers/google/models/gemini-2.5-flash"

    let router = Router()
    router.get("/") { _, _ -> String in
      let request = GenerateContentRequest().with {
        $0.model = model
        $0.contents = [
          Content().with { content in
            content.role = "user"
            content.parts = [
              Part().with { part in
                part.data = .text(
                  "What's a good name for a flower shop that specializes in selling bouquets of dried flowers?"
                )
              }
            ]
          }
        ]
      }
      let response = try await client.generateContent(request: request)
      if case .text(let text) = response.candidates.first?.content?.parts.first?.data {
        return text
      }
      return "No response generated.\n"
    }

    let app = Application(
      router: router,
      configuration: .init(address: .hostname(host, port: port))
    )
    try await app.runService()
  }
}

What's next