Men-deploy database vektor PostgreSQL di GKE


Tutorial ini menunjukkan cara men-deploy cluster database vektor PostgreSQL di Google Kubernetes Engine (GKE).

PostgreSQL dilengkapi dengan berbagai modul dan ekstensi yang memperluas fungsi database. Dalam tutorial ini, Anda akan menginstal ekstensi pgvector di cluster PostgreSQL yang ada dan di-deploy ke GKE. Ekstensi Pgvector memungkinkan Anda menyimpan vektor di tabel database dengan menambahkan jenis vektor ke PostgreSQL. Pgvector juga menyediakan penelusuran kemiripan dengan menjalankan kueri SQL umum.

Kami menyederhanakan deployment ekstensi PGvector dengan terlebih dahulu men-deploy operator CloudnativePG, karena operator menyediakan versi ekstensi yang dipaketkan.

Tutorial ini ditujukan untuk administrator dan arsitek platform cloud, engineer ML, dan profesional MLOps (DevOps) yang tertarik untuk men-deploy cluster database PostgreSQL di GKE.

Tujuan

Dalam tutorial ini, Anda akan mempelajari cara:

  • Men-deploy infrastruktur GKE untuk PostgreSQL.
  • Instal ekstensi pgvector di cluster PostgreSQL yang di-deploy ke GKE.
  • Men-deploy dan mengonfigurasi operator PostgreSQL CloudNativePG dengan Helm.
  • Upload set data demo dan jalankan kueri penelusuran dengan Jupyter Notebook.

Biaya

Dalam dokumen ini, Anda akan menggunakan komponen Google Cloudyang dapat ditagih berikut:

Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda, gunakan kalkulator harga. Pengguna Google Cloud baru mungkin memenuhi syarat untuk mendapatkan uji coba gratis.

Setelah menyelesaikan tugas yang dijelaskan dalam dokumen ini, Anda dapat menghindari penagihan berkelanjutan dengan menghapus resource yang Anda buat. Untuk mengetahui informasi selengkapnya, lihat Pembersihan.

Sebelum memulai

Dalam tutorial ini, Anda akan menggunakan Cloud Shell untuk menjalankan perintah. Cloud Shell adalah lingkungan shell untuk mengelola resource yang dihosting di Google Cloud. Cloud Shell telah diinstal dengan alat command line Google Cloud CLI, kubectl, Helm, dan Terraform. Jika tidak menggunakan Cloud Shell, Anda harus menginstal Google Cloud CLI.

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.
  3. To initialize the gcloud CLI, run the following command:

    gcloud init
  4. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  5. Make sure that billing is enabled for your Google Cloud project.

  6. Enable the Cloud Resource Manager, Compute Engine, GKE, and IAM Service Account Credentials APIs:

    gcloud services enable cloudresourcemanager.googleapis.com compute.googleapis.com container.googleapis.com iamcredentials.googleapis.com
  7. Install the Google Cloud CLI.
  8. To initialize the gcloud CLI, run the following command:

    gcloud init
  9. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  10. Make sure that billing is enabled for your Google Cloud project.

  11. Enable the Cloud Resource Manager, Compute Engine, GKE, and IAM Service Account Credentials APIs:

    gcloud services enable cloudresourcemanager.googleapis.com compute.googleapis.com container.googleapis.com iamcredentials.googleapis.com
  12. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/compute.securityAdmin, roles/compute.viewer, roles/container.clusterAdmin, roles/container.admin, roles/iam.serviceAccountAdmin, roles/iam.serviceAccountUser

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE
    • Replace PROJECT_ID with your project ID.
    • Replace USER_IDENTIFIER with the identifier for your user account. For example, user:myemail@example.com.

    • Replace ROLE with each individual role.

Menyiapkan lingkungan Anda

Untuk menyiapkan lingkungan Anda dengan Cloud Shell, ikuti langkah-langkah berikut:

  1. Tetapkan variabel lingkungan untuk project, region, dan awalan resource cluster Kubernetes:

    export PROJECT_ID=PROJECT_ID
    export KUBERNETES_CLUSTER_PREFIX=postgres
    export REGION=us-central1
    
    • Ganti PROJECT_ID dengan project ID Google Cloud Anda.

    Tutorial ini menggunakan region us-central1.

  2. Clone repositori kode contoh dari GitHub:

    git clone https://github.com/GoogleCloudPlatform/kubernetes-engine-samples
    
  3. Buka direktori postgres-pgvector:

    cd kubernetes-engine-samples/databases/postgres-pgvector
    

Membuat infrastruktur cluster

Di bagian ini, Anda akan menjalankan skrip Terraform untuk membuat cluster GKE regional pribadi yang sangat tersedia untuk men-deploy database PostgreSQL.

Anda dapat memilih untuk men-deploy PostgreSQL menggunakan cluster Standard atau Autopilot. Masing-masing memiliki kelebihan dan model penetapan harga yang berbeda.

Autopilot

Untuk men-deploy infrastruktur cluster Autopilot, jalankan perintah berikut di Cloud Shell:

export GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token)
terraform -chdir=../postgresql-cloudnativepg/terraform/gke-autopilot init
terraform -chdir=../postgresql-cloudnativepg/terraform/gke-autopilot apply \
-var project_id=${PROJECT_ID} \
-var region=${REGION} \
-var cluster_prefix=${KUBERNETES_CLUSTER_PREFIX}

GKE mengganti variabel berikut saat runtime:

  • GOOGLE_OAUTH_ACCESS_TOKEN menggunakan perintah gcloud auth print-access-token untuk mengambil token akses yang mengautentikasi interaksi dengan berbagai Google Cloud API
  • PROJECT_ID, REGION, dan KUBERNETES_CLUSTER_PREFIX adalah variabel lingkungan yang ditentukan di bagian Siapkan lingkungan Anda dan ditetapkan ke variabel baru yang relevan untuk cluster Autopilot yang Anda buat.

Saat diminta, ketik yes.

Terraform membuat resource berikut:

  • Jaringan VPC kustom dan subnet pribadi untuk node Kubernetes.
  • Cloud Router untuk mengakses internet melalui Penafsiran Alamat Jaringan (NAT).
  • Cluster GKE pribadi di region us-central1.
  • ServiceAccount dengan izin logging dan pemantauan untuk cluster.
  • Konfigurasi Google Cloud Managed Service for Prometheus untuk pemantauan dan pemberitahuan cluster.

Outputnya mirip dengan hal berikut ini:

...
Apply complete! Resources: 11 added, 0 changed, 0 destroyed.
...

Standar

Untuk men-deploy infrastruktur cluster Standard, jalankan perintah berikut di Cloud Shell:

export GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token)
terraform -chdir=../postgresql-cloudnativepg/terraform/gke-standard init
terraform -chdir=../postgresql-cloudnativepg/terraform/gke-standard apply \
-var project_id=${PROJECT_ID} \
-var region=${REGION} \
-var cluster_prefix=${KUBERNETES_CLUSTER_PREFIX}

GKE mengganti variabel berikut saat runtime:

  • GOOGLE_OAUTH_ACCESS_TOKEN menggunakan perintah gcloud auth print-access-token untuk mengambil token akses yang mengautentikasi interaksi dengan berbagai Google Cloud API.
  • PROJECT_ID, REGION, dan KUBERNETES_CLUSTER_PREFIX adalah variabel lingkungan yang ditentukan di bagian Menyiapkan lingkungan dan ditetapkan ke variabel baru yang relevan untuk cluster Standar yang Anda buat.

Saat diminta, ketik yes. Anda mungkin perlu menunggu beberapa menit agar perintah ini selesai dan cluster akan menampilkan status siap.

Terraform membuat resource berikut:

  • Jaringan VPC kustom dan subnet pribadi untuk node Kubernetes.
  • Cloud Router untuk mengakses internet melalui Penafsiran Alamat Jaringan (NAT).
  • Cluster GKE pribadi di region us-central1 dengan penskalaan otomatis diaktifkan (satu hingga dua node per zona).
  • ServiceAccount dengan izin logging dan pemantauan untuk cluster.
  • Konfigurasi Google Cloud Managed Service for Prometheus untuk pemantauan dan pemberitahuan cluster.

Outputnya mirip dengan hal berikut ini:

...
Apply complete! Resources: 14 added, 0 changed, 0 destroyed.
...

Hubungkan ke cluster

Konfigurasi kubectl untuk mengambil kredensial dan berkomunikasi dengan cluster GKE baru Anda:

gcloud container clusters get-credentials \
    ${KUBERNETES_CLUSTER_PREFIX}-cluster --region ${REGION} --project ${PROJECT_ID}

Men-deploy operator CloudNativePG

Deploy CloudNativePG ke cluster Kubernetes Anda menggunakan diagram Helm:

  1. Periksa versi Helm:

    helm version
    

    Update versi jika lebih lama dari 3.13:

    curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
    
  2. Tambahkan repositori Helm Chart operator CloudNativePG:

    helm repo add cnpg https://cloudnative-pg.github.io/charts
    
  3. Deploy operator CloudNativePG menggunakan alat command line Helm:

    helm upgrade --install cnpg \
        --namespace cnpg-system \
        --create-namespace \
        cnpg/cloudnative-pg
    

    Outputnya mirip dengan hal berikut ini:

    Release "cnpg" does not exist. Installing it now.
    NAME: cnpg
    LAST DEPLOYED: Fri Oct 13 13:52:36 2023
    NAMESPACE: cnpg-system
    STATUS: deployed
    REVISION: 1
    TEST SUITE: None
    ...
    

Men-deploy database vektor PostgreSQL

Di bagian ini, Anda akan men-deploy database vektor PostgreSQL.

  1. Buat namespace pg-ns untuk database:

    kubectl create ns pg-ns
    
  2. Terapkan manifes untuk men-deploy cluster PostgreSQL. Manifes cluster mengaktifkan ekstensi pgvector.

    kubectl apply -n pg-ns -f manifests/01-basic-cluster/postgreSQL_cluster.yaml
    

    Manifes postgreSQL_cluster.yaml menjelaskan Deployment:

    apiVersion: postgresql.cnpg.io/v1
    kind: Cluster
    metadata:
      name: gke-pg-cluster
    spec:
      description: "Standard GKE PostgreSQL cluster"
      imageName: ghcr.io/cloudnative-pg/postgresql:16.2
      enableSuperuserAccess: true
      instances: 3
      startDelay: 300
      primaryUpdateStrategy: unsupervised
      postgresql:
        pg_hba:
          - host all all 10.48.0.0/20 md5
      bootstrap:
        initdb:
          postInitTemplateSQL:
            - CREATE EXTENSION IF NOT EXISTS vector;
          database: app
      storage:
        storageClass: premium-rwo
        size: 2Gi
      resources:
        requests:
          memory: "1Gi"
          cpu: "1000m"
        limits:
          memory: "1Gi"
          cpu: "1000m"
      affinity:
        enablePodAntiAffinity: true
        tolerations:
        - key: cnpg.io/cluster
          effect: NoSchedule
          value: gke-pg-cluster
          operator: Equal
        additionalPodAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 1
            podAffinityTerm:
              labelSelector:
                matchExpressions:
                - key: app.component
                  operator: In
                  values:
                  - "pg-cluster"
              topologyKey: topology.kubernetes.io/zone
      monitoring:
        enablePodMonitor: true
  3. Periksa status cluster:

    kubectl get cluster -n pg-ns --watch
    

    Tunggu hingga output menampilkan status Cluster in healthy state sebelum Anda melanjutkan ke langkah berikutnya.

Menjalankan kueri dengan notebook Vertex AI Colab Enterprise

Di bagian ini, Anda akan mengupload vektor ke tabel PostgreSQL dan menjalankan kueri penelusuran semantik menggunakan sintaksis SQL.

Anda terhubung ke database PostgreSQL menggunakan Colab Enterprise. Anda menggunakan template runtime khusus untuk men-deploy ke postgres-vpc, sehingga notebook dapat berkomunikasi dengan resource di cluster GKE.

Untuk mengetahui informasi selengkapnya tentang Vertex AI Colab Enterprise, lihat dokumentasi Colab Enterprise.

Membuat template runtime

Untuk membuat template runtime Colab Enterprise:

  1. Di konsol Google Cloud, buka halaman Runtime Templates Colab Enterprise dan pastikan project Anda dipilih:

    Buka Template Runtime

  2. Klik Template Baru. Halaman Create new runtime template akan muncul.

  3. Di bagian Runtime basics:

    • Di kolom Nama tampilan, masukkan pgvector-connect.
    • Di menu drop-down Region, pilih us-central1. Region ini sama dengan cluster GKE Anda.
  4. Di bagian Configure compute:

    • Di menu drop-down Machine type, pilih e2-standard-2.
    • Di kolom Disk size, masukkan 30.
  5. Di bagian Networking and security:

    • Di menu drop-down Network, pilih jaringan tempat cluster GKE Anda berada.
    • Di menu drop-down Subnetwork, pilih subnetwork yang sesuai.
    • Hapus centang pada kotak Aktifkan akses internet publik.
  6. Untuk menyelesaikan pembuatan template runtime, klik Create. Template runtime Anda akan muncul dalam daftar di tab Runtime templates.

Membuat runtime

Untuk membuat runtime Colab Enterprise:

  1. Dalam daftar template runtime untuk template yang baru saja Anda buat, di kolom Actions, klik , lalu klik Create runtime. Panel Create Vertex AI Runtime akan muncul.

  2. Untuk membuat runtime berdasarkan template Anda, klik Create.

  3. Di tab Runtimes yang terbuka, tunggu hingga status bertransisi ke Healthy.

Mengimpor notebook

Untuk mengimpor notebook di Colab Enterprise:

  1. Buka tab My Notebooks, lalu klik Import. Panel Import notebooks akan muncul.

  2. Di Sumber impor, pilih URL.

  3. Di bagian URL Notebook, masukkan link berikut:

    https://raw.githubusercontent.com/epam/kubernetes-engine-samples/internal_lb/databases/postgres-pgvector/manifests/02-notebook/vector-database.ipynb
    
  4. Klik Import.

Menghubungkan ke runtime dan menjalankan kueri

Untuk terhubung ke runtime dan menjalankan kueri:

  1. Di notebook, di samping tombol Connect, klik Additional connection options. Panel Connect to Vertex AI Runtime akan muncul.

  2. Pilih Connect to a runtime, lalu pilih Connect to an existing Runtime.

  3. Pilih runtime yang Anda luncurkan, lalu klik Connect.

  4. Untuk menjalankan sel notebook, klik tombol Run cell di samping setiap sel kode.

Notebook berisi sel kode dan teks yang menjelaskan setiap blok kode. Menjalankan sel kode akan mengeksekusi perintahnya dan menampilkan output. Anda dapat menjalankan sel secara berurutan, atau menjalankan setiap sel sesuai kebutuhan.

Pembersihan

Agar tidak perlu membayar biaya pada akun Google Cloud Anda untuk resource yang digunakan dalam tutorial ini, hapus project yang berisi resource tersebut, atau simpan project dan hapus setiap resource.

Menghapus project

Cara termudah untuk menghindari penagihan adalah dengan menghapus project yang Anda buat untuk tutorial ini.

Delete a Google Cloud project:

gcloud projects delete PROJECT_ID

Jika Anda menghapus project ini, berarti pembersihan telah selesai. Jika Anda tidak menghapus project, lanjutkan untuk menghapus resource individual.

Menghapus resource satu per satu

  1. Menetapkan variabel lingkungan.

    export PROJECT_ID=${PROJECT_ID}
    export KUBERNETES_CLUSTER_PREFIX=postgres
    export REGION=us-central1
    
  2. Jalankan perintah terraform destroy:

    export GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token)
    terraform  -chdir=../postgresql-cloudnativepg/terraform/FOLDER destroy \
    -var project_id=${PROJECT_ID} \
    -var region=${REGION} \
    -var cluster_prefix=${KUBERNETES_CLUSTER_PREFIX}
    

    Ganti FOLDER dengan gke-autopilot atau gke-standard, bergantung pada jenis cluster GKE yang Anda buat.

    Saat diminta, ketik yes.

Langkah berikutnya