使用 Ollama 和 Open-WebUI 部署 Gemma

借助 GDC 沙盒 AI 优化 SKU 中包含的企业级 NVIDIA GPU,您可以开发和测试要求苛刻的 AI 训练和推理应用,例如生成式 AI。

Gemma 是一款基于 Gemini 技术的轻量级大语言模型。本教程指南介绍了如何在 GDC 沙盒上使用 OllamaOpen-WebUI 部署 Gemma,并具有以下目标。

  • 在配备 GPU 的 AI 优化型 GDC 沙盒上部署使用 Gemma 模型的 Ollama。
  • 通过 Open-WebUI 界面在 Ollama 服务的专用端点向该服务发送提示。

准备工作

GDC Sandbox 中的 GPU 包含在组织基础架构集群中。

  • 如需针对组织基础架构集群运行命令,请确保您拥有 org-1-infra 集群的 kubeconfig,如处理集群中所述:

    • 使用 gdcloud 命令行工具进行配置和身份验证,并
    • 为组织基础架构集群生成 kubeconfig 文件,并将其路径分配给环境变量 KUBECONFIG
  • 确保用户已获分配项目 sandbox-gpu-projectsandbox-gpu-admin 角色。 默认情况下,该角色会分配给 platform-admin 用户。您可以登录 platform-admin 并运行以下命令,将该角色分配给其他用户:

    kubectl --kubeconfig ${KUBECONFIG} create rolebinding ${NAME} --role=sandbox-gpu-admin \
    --user=${USER} --namespace=sandbox-gpu-project
    
  • 请务必按照使用 Artifact Registry 中的说明设置 Artifact Registry 代码库,并登录以便能够将映像推送到制品注册表和从制品注册表中拉取映像。

使用 Ollama 和 Open-WebUI 部署 Gemma 模型

部署通过一组 Kubernetes 配置文件(YAML 清单)进行编排,每个文件定义一个特定的组件或服务。

  1. 创建一个预下载了 Gemma 的 Dockerfile。

     # Use an NVIDIA CUDA base image for GPU support
     FROM nvidia/cuda:12.3.1-cudnn8-devel-ubuntu22.04
    
     # Install Ollama
     # This uses Ollamas official installation script, which adds Ollama to /usr/local/bin
     RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates
     RUN curl -fsSL https://ollama.com/install.sh -o install.sh
     RUN chmod +x install.sh
     RUN ./install.sh && \
         rm -rf /var/lib/apt/lists/*
    
     # Set environment variables for Ollama (optional, but good practice)
     ENV OLLAMA_HOST="0.0.0.0"
     # ENV OLLAMA_MODELS="/usr/local/ollama/models" # Default is /root/.ollama
     # If you want to customize the model storage path within the container, set OLLAMA_MODELS
     # and then ensure you create and populate that directory. Default is usually fine for pre-downloaded.
    
     # --- Predownload Gemma Model ---
     # This step starts Ollama server in the background, pulls the model,
     # and then kills the server to allow the Docker build to continue.
     # This approach works around Docker''s RUN command limitations for services.
    
     RUN ollama serve & \
         sleep 5 && \
         # Give the Ollama server a moment to start up
         # Use --retry and --retry-connrefused to handle startup delays
         curl --retry 10 --retry-connrefused -s http://localhost:11434 || true && \
         echo "Attempting to pull gemma:7b..." && \
         ollama pull gemma:7b && \
         echo "Model pull complete. Cleaning up background Ollama process." && \
         pkill ollama || true # Gracefully kill the ollama serve process
    
     # Expose Ollama's default port
     EXPOSE 11434
    
     # Command to run Ollama server when the container starts
     CMD ["ollama", "serve"]
    
    
  1. 构建 Docker 映像并将其上传到 Artifact Registry 代码库。

    docker build -t ollama-gemma .
    docker tag ollama-gemma REGISTRY_REPOSITORY_URL/ollama-gemma:latest
    docker push REGISTRY_REPOSITORY_URL/ollama-gemma:latest
    

    替换以下内容:

    • REGISTRY_REPOSITORY_URL 替换为代码库网址。
  2. 创建一个 Secret 来保存 Docker 凭据。

    
    export SECRET=DOCKER_REGISTRY_SECRET
    export DOCKER_TEST_CONFIG=~/.docker/config.json 
    kubectl --kubeconfig ${KUBECONFIG}$ create secret docker-registry ${SECRET} --from-file=.dockerconfigjson=${DOCKER_TEST_CONFIG} -n sandbox-gpu-project
    

    替换以下内容:

    • DOCKER_REGISTRY_SECRET Secret 的名称。
  3. 创建文件 ollama-deployment.yaml 以定义 Ollama AI 引擎部署:

    Ollama 服务器的部署需要一个 GPU。

      apiVersion: apps/v1
      kind: Deployment
      metadata:
        annotations:
          deployment.kubernetes.io/revision: "9"
        name: ollama
        namespace: sandbox-gpu-project
      spec:
        progressDeadlineSeconds: 600
        replicas: 1
        revisionHistoryLimit: 10
        selector:
          matchLabels:
            app: ollama
        strategy:
          rollingUpdate:
            maxSurge: 25%
            maxUnavailable: 25%
          type: RollingUpdate
        template:
          metadata:
            creationTimestamp: null
            labels:
              app: ollama
              egress.networking.gke.io/enabled: "true"
          spec:
            containers:
              - name: ollama
                image: REGISTRY_REPOSITORY_URL/ollama-gemma:latest
                imagePullPolicy: Always
                ports:
                  - containerPort: 11434
                    protocol: TCP
                resources:
                  limits:
                    nvidia.com/gpu-pod-NVIDIA_H100_80GB_HBM3: "1"
                  requests:
                    nvidia.com/gpu-pod-NVIDIA_H100_80GB_HBM3: "1"
                env:
                  - name: OLLAMA_HOST
                    value: 0.0.0.0
                  - name: OLLAMA_ORIGINS
                    value: http://localhost:8080,http://ollama-webui.ollama-llm.svc.cluster.local:8080,http://ollama-webui:8080
                securityContext:
                  seLinuxOptions:
                    type: unconfined_t
                terminationMessagePath: /dev/termination-log
                terminationMessagePolicy: File
            imagePullSecrets:
            - name: DOCKER_REGISTRY_SECRET
            dnsConfig:
              nameservers:
                - 8.8.8.8
            dnsPolicy: ClusterFirst
            restartPolicy: Always
            schedulerName: default-scheduler
            terminationGracePeriodSeconds: 30
    
    

    替换以下内容:

    • REGISTRY_REPOSITORY_URL:代码库网址。
    • DOCKER_REGISTRY_SECRET:Secret 的名称。
  4. 创建文件 ollama-service.yaml 以在内部公开 Ollama 服务器。

    apiVersion: v1
    kind: Service
    metadata:
      name: ollama
      namespace: sandbox-gpu-project
      annotations:
        metallb.universe.tf/ip-allocated-from-pool: lb-address-pool-0-ptleg
    spec:
      type: LoadBalancer
      selector:
        app: ollama
      ports:
        - port: 11434
          nodePort: 30450
      ipFamilyPolicy: SingleStack
      ipFamilies:
        - IPv4
      clusterIPs:
        - 10.1.122.216
      clusterIP: 10.1.122.216
    
  5. 应用清单

    kubectl --kubeconfig ${KUBECONFIG} apply -f ollama-deployment.yaml
    kubectl --kubeconfig ${KUBECONFIG} apply -f ollama-service.yaml
    
  6. 确保 ollama pod 正在运行。

    kubectl --kubeconfig ${KUBECONFIG} get deployments -n sandbox-gpu-project
    kubectl --kubeconfig ${KUBECONFIG} get service -n sandbox-gpu-project
    
  7. 记下输出中 Ollama 服务 OLLAMA_BASE_END_POINT 的外部 IP

    kubectl --kubeconfig ${KUBECONFIG} get service ollama \
          -n sandbox-gpu-project -o jsonpath='{.status.loadBalancer.ingress[*].ip}'
    
  8. 创建文件 openweb-ui-deployment.yaml 以部署 Open-WebUI 界面。

      apiVersion: apps/v1
      kind: Deployment
      metadata:
        name: ollama-webui
        namespace: sandbox-gpu-project
        labels:
          app: ollama-webui
        annotations:
          deployment.kubernetes.io/revision: "5"
      spec:
        replicas: 1
        selector:
          matchLabels:
            app: ollama-webui
        strategy:
          type: RollingUpdate
          rollingUpdate:
            maxSurge: 25%
            maxUnavailable: 25%
        progressDeadlineSeconds: 600
        revisionHistoryLimit: 10
        template:
          metadata:
            labels:
              app: ollama-webui
            creationTimestamp: null
          spec:
            containers:
              - name: ollama-webui
                image: ghcr.io/open-webui/open-webui:main
                imagePullPolicy: IfNotPresent
                ports:
                  - name: http
                    containerPort: 8080
                    protocol: TCP
                env:
                  - name: OLLAMA_BASE_URL
                    value: OLLAMA_BASE_END_POINT
                  - name: PORT
                    value: "8080"
                terminationMessagePath: /dev/termination-log
                terminationMessagePolicy: File
            restartPolicy: Always
            dnsPolicy: ClusterFirst
            schedulerName: default-scheduler
            terminationGracePeriodSeconds: 30
    

    替换以下内容:

    • OLLAMA_BASE_END_POINT:Ollama 服务的外部 IP 地址。
  9. 创建文件 ollama-webui-service.yaml 以对外公开开放式 Web 界面。

    apiVersion: v1
    kind: Service
    metadata:
      name: ollama-webui
      namespace: sandbox-gpu-project
      annotations:
        metallb.universe.tf/ip-allocated-from-pool: lb-address-pool-0-ptleg
    spec:
      type: LoadBalancer
      ipFamilyPolicy: SingleStack
      ipFamilies:
      - IPv4
      clusterIPs:
      - 10.1.104.52
      clusterIP: 10.1.104.52
      ports:
      - port: 80
        targetPort: 8080
        nodePort: 32351
      selector:
        app: ollama-webui
    
  10. 针对集群应用清单 openweb-ui-deployment.yamlollama-webui-service.yaml

        kubectl --kubeconfig ${KUBECONFIG} apply -f openweb-ui-deployment.yaml
        kubectl --kubeconfig ${KUBECONFIG} apply -f ollama-webui-service.yaml
    
  11. 创建项目网络政策,以允许来自外部 IP 地址的入站流量。

    kubectl --kubeconfig ${KUBECONFIG} apply -f - <<EOF
    apiVersion: networking.global.gdc.goog/v1
    kind: ProjectNetworkPolicy
    metadata:
      namespace: sandbox-gpu-project
      name: allow-inbound-traffic-from-external
    spec:
      policyType: Ingress
      subject:
        subjectType: UserWorkload
      ingress:
      - from:
        - ipBlock:
            cidr: 0.0.0.0/0
    EOF
    
  12. 运行以下命令,确定 Ollama 服务的外部 IP。请记下该值,以便在后续步骤中使用,届时您将使用该值替换 OPEN_WEB_UI_ENDPOINT

    kubectl --kubeconfig ${KUBECONFIG} get service -n sandbox-gpu-project
    
  13. 打开 Google Chrome,然后使用您在上一步中找到的外部 IP 地址输入网址。您现在可以通过 Open Web 界面与 Gemma 模型互动。

    http://OPEN_WEB_UI_ENDPOINT/