Deploy a Swift service to Cloud Run

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:

  1. Initialize a new executable Swift package:

    mkdir CloudRunGemini
    cd CloudRunGemini
    swift package init --name CloudRunGemini --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 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:

  1. Import the required modules:

    import Foundation
    import GoogleCloudAIPlatformV1
    import Hummingbird

  2. Define the application entry point:

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

  3. Read the GOOGLE_CLOUD_PROJECT environment variable (configured during deployment) along with the 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 CloudRunGemini 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/CloudRunGemini /app/CloudRunGemini
    USER swift:swift
    EXPOSE 8080
    
    ENTRYPOINT ["/app/CloudRunGemini"]
    

    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 CloudRunGemini 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
    

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:

  1. Set your project ID and region environment variables:

    export PROJECT_ID=$(gcloud config get project)
    export REGION=us-central1
    
  2. Create 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"
    
  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}/cloud-run-apps/cloud-run-gemini"
    
  4. 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}." \
        --role="roles/aiplatform.user" \
        --condition=None
    
  5. Deploy the container image to Cloud Run. Choose one of the following authentication options:

    • Use --no-allow-unauthenticated to require IAM authentication (recommended for internal services or when your organization enforces domain-restricted sharing).
    • Use --allow-unauthenticated to 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}." \
        --no-allow-unauthenticated \
        --set-env-vars="GOOGLE_CLOUD_PROJECT=${PROJECT_ID}"
    

Verify the deployed service

To test the deployed service, follow these steps:

  1. Retrieve the URL of the deployed Cloud Run service:

    SERVICE_URL=$(gcloud run services describe cloud-run-gemini \
        --region="${REGION}" \
        --format="value(status.url)")
    
  2. Send a request to the service.

    If you deployed with --no-allow-unauthenticated, include an identity token in the Authorization header:

    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:

  1. Delete the Cloud Run service:

    gcloud run services delete cloud-run-gemini --region="${REGION}"
    
  2. Delete the Artifact Registry repository:

    gcloud artifacts repositories delete cloud-run-apps --location="${REGION}"
    
  3. Remove the IAM policy binding from the service account:

    gcloud projects remove-iam-policy-binding "${PROJECT_ID}" \
        --member="serviceAccount:cloud-run-gemini@${PROJECT_ID}." \
        --role="roles/aiplatform.user" \
        --condition=None
    
  4. Delete the service account:

    gcloud iam service-accounts delete \
        "cloud-run-gemini@${PROJECT_ID}."
    
  5. 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/CloudRunGemini/CloudRunGemini.swift:

import Foundation
import GoogleCloudAIPlatformV1
import Hummingbird

@main
struct CloudRunGemini {
  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