GKE에 PostgreSQL 벡터 데이터베이스 배포


이 튜토리얼에서는 Google Kubernetes Engine(GKE)에 PostgreSQL 벡터 데이터베이스 클러스터를 배포하는 방법을 보여줍니다.

PostgreSQL에는 데이터베이스 기능을 확장하는 다양한 모듈과 확장 프로그램이 함께 제공됩니다. 이 튜토리얼에서는 GKE에 배포된 기존 PostgreSQL 클러스터에 pgvector 확장 프로그램을 설치합니다. Pgvector 확장 프로그램을 사용하면 PostgreSQL에 벡터 유형을 추가하여 데이터베이스 테이블에 벡터를 저장할 수 있습니다. Pgvector는 일반적인 SQL 쿼리를 실행하여 유사성 검색도 제공합니다.

연산자가 확장 프로그램의 번들 버전을 제공하므로 먼저 CloudnativePG 연산자를 배포하여 PGvector 확장 프로그램 배포를 단순화합니다.

이 튜토리얼은 GKE에서 PostgreSQL 데이터베이스 클러스터를 배포하는 데 관심이 있는 클라우드 플랫폼 관리자 및 설계자, ML 엔지니어, MLOps(DevOps) 전문가를 대상으로 합니다.

목표

이 튜토리얼에서는 다음을 수행하는 방법을 알아봅니다.

  • PostgreSQL용 GKE 인프라 배포
  • GKE에 배포된 PostgreSQL 클러스터에 pgvector 확장 프로그램 설치
  • Helm을 사용하여 CloudNativePG PostgreSQL 연산자 배포 및 구성
  • Jupyter 노트북으로 데모 데이터 세트 업로드 및 검색어 실행

비용

이 문서에서는 비용이 청구될 수 있는 다음과 같은 Google Cloud 구성요소를 사용합니다.

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용하세요. Google Cloud를 처음 사용하는 사용자는 무료 체험판을 사용할 수 있습니다.

이 문서에 설명된 태스크를 완료했으면 만든 리소스를 삭제하여 청구가 계속되는 것을 방지할 수 있습니다. 자세한 내용은 삭제를 참조하세요.

시작하기 전에

이 튜토리얼에서는 Cloud Shell을 사용하여 명령어를 실행합니다. Cloud Shell은 Google Cloud에서 호스팅되는 리소스를 관리하는 데 사용되는 셸 환경입니다. Google Cloud CLI, kubectl, Helm, Terraform 명령줄 도구가 사전에 설치되어 있습니다. Cloud Shell을 사용하지 않는 경우에는 Google Cloud CLI를 설치해야 합니다.

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud CLI를 설치합니다.
  3. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    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. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  6. Cloud Resource Manager, Compute Engine, GKE, and IAM Service Account Credentials API를 사용 설정합니다.

    gcloud services enable cloudresourcemanager.googleapis.com compute.googleapis.com container.googleapis.com iamcredentials.googleapis.com
  7. Google Cloud CLI를 설치합니다.
  8. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    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. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  11. Cloud Resource Manager, Compute Engine, GKE, and IAM Service Account Credentials API를 사용 설정합니다.

    gcloud services enable cloudresourcemanager.googleapis.com compute.googleapis.com container.googleapis.com iamcredentials.googleapis.com
  12. Google 계정에 역할을 부여합니다. 다음 각 IAM 역할에 대해 다음 명령어를 한 번씩 실행합니다. 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:EMAIL_ADDRESS" --role=ROLE
    • PROJECT_ID를 프로젝트 ID로 바꿉니다.
    • EMAIL_ADDRESS를 이메일 주소로 바꿉니다.
    • ROLE을 각 개별 역할로 바꿉니다.

환경 설정

Cloud Shell로 환경을 설정하려면 다음 단계를 따르세요.

  1. 프로젝트, 리전, Kubernetes 클러스터 리소스 프리픽스의 환경 변수를 설정합니다.

    export PROJECT_ID=PROJECT_ID
    export KUBERNETES_CLUSTER_PREFIX=postgres
    export REGION=us-central1
    
    • PROJECT_ID를 Google Cloud 프로젝트 ID로 바꿉니다.

    이 튜토리얼에서는 us-central1 리전을 사용합니다.

  2. GitHub에서 샘플 코드 저장소를 클론합니다.

    git clone https://github.com/GoogleCloudPlatform/kubernetes-engine-samples
    
  3. postgres-pgvector 디렉터리로 이동합니다.

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

클러스터 인프라 만들기

이 섹션에서는 Terraform 스크립트를 실행하여 PostgreSQL 데이터베이스를 배포하기 위해 가용성이 높은 비공개 리전 GKE 클러스터를 만듭니다.

Standard 또는 Autopilot 클러스터를 사용하여 PostgreSQL을 배포할 수 있습니다. 각 유형은 고유한 장점이 있으며 서로 다른 가격 책정 모델을 제공합니다.

Autopilot

Autopilot 클러스터 인프라를 배포하려면 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는 런타임 시 다음 변수를 바꿉니다.

  • GOOGLE_OAUTH_ACCESS_TOKENgcloud auth print-access-token 명령어를 사용하여 다양한 Google Cloud API와의 상호작용을 인증하는 액세스 토큰을 검색합니다.
  • PROJECT_ID, REGION, KUBERNETES_CLUSTER_PREFIX환경 설정 섹션에 정의된 환경 변수이며 생성 중인 Autopilot 클러스터의 새 관련 변수에 할당됩니다.

메시지가 표시되면 yes를 입력합니다.

Terraform에서 다음 리소스를 만듭니다.

  • Kubernetes 노드의 커스텀 VPC 네트워크 및 비공개 서브넷
  • 네트워크 주소 변환(NAT)을 통해 인터넷에 액세스하는 Cloud Router
  • us-central1 리전의 비공개 GKE 클러스터
  • 클러스터에 대한 로깅 및 모니터링 권한이 있는 ServiceAccount
  • 클러스터 모니터링 및 알림을 위한 Google Cloud Managed Service for Prometheus 구성

출력은 다음과 비슷합니다.

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

표준

Standard 클러스터 인프라를 배포하려면 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는 런타임 시 다음 변수를 바꿉니다.

  • GOOGLE_OAUTH_ACCESS_TOKENgcloud auth print-access-token 명령어를 사용하여 다양한 Google Cloud API와의 상호작용을 인증하는 액세스 토큰을 검색합니다.
  • PROJECT_ID, REGION, KUBERNETES_CLUSTER_PREFIX환경 설정 섹션에 정의된 환경 변수이며 만든 Standard 클러스터의 새 관련 변수에 할당됩니다.

메시지가 표시되면 yes를 입력합니다. 이러한 명령어가 완료되고 클러스터에 준비 상태가 표시되는 데 몇 분 정도 걸릴 수 있습니다.

Terraform에서 다음 리소스를 만듭니다.

  • Kubernetes 노드의 커스텀 VPC 네트워크 및 비공개 서브넷
  • 네트워크 주소 변환(NAT)을 통해 인터넷에 액세스하는 Cloud Router
  • 자동 확장이 사용 설정된 us-central1 리전의 비공개 GKE 클러스터(영역당 노드 1~2개)
  • 클러스터에 대한 로깅 및 모니터링 권한이 있는 ServiceAccount
  • 클러스터 모니터링 및 알림을 위한 Google Cloud Managed Service for Prometheus 구성

출력은 다음과 비슷합니다.

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

클러스터에 연결

사용자 인증 정보를 가져오고 새 GKE 클러스터와 통신하도록 kubectl을 구성합니다.

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

CloudNativePG 연산자 배포

Helm 차트를 사용하여 Kubernetes 클러스터에 CloudNativePG를 배포합니다.

  1. Helm 버전을 확인합니다.

    helm version
    

    3.13 이전인 경우 버전을 업데이트합니다.

    curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
    
  2. CloudNativePG 연산자 Helm 차트 저장소를 추가합니다.

    helm repo add cnpg https://cloudnative-pg.github.io/charts
    
  3. Helm 명령줄 도구를 사용하여 CloudNativePG 연산자를 배포합니다.

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

    출력은 다음과 비슷합니다.

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

PostgreSQL 벡터 데이터베이스 배포

이 섹션에서는 PostgreSQL 벡터 데이터베이스를 배포합니다.

  1. 데이터베이스의 네임스페이스 pg-ns를 만듭니다.

    kubectl create ns pg-ns
    
  2. 매니페스트를 적용하여 PostgreSQL 클러스터를 배포합니다. 클러스터 매니페스트는 pgvector 확장 프로그램을 사용 설정합니다.

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

    postgreSQL_cluster.yaml 매니페스트는 배포를 설명합니다.

    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. 클러스터의 상태를 확인합니다.

    kubectl get cluster -n pg-ns --watch
    

    다음 단계로 이동하기 전에 출력에 Cluster in healthy state 상태가 표시될 때까지 기다립니다.

Jupyter 노트북으로 데모 데이터 세트 업로드 및 검색어 실행

이 섹션에서는 벡터를 PostgreSQL 테이블에 업로드하고 SQL 구문을 사용하여 시맨틱 검색 쿼리를 실행합니다.

다음 예시에서는 다양한 장르의 도서 목록이 포함된 CSV 파일의 데이터 세트를 사용합니다. Pgvector는 검색엔진 역할을 하며 생성된 포드는 Pgvector 데이터베이스를 쿼리하는 클라이언트 역할을 합니다.

  1. PostgreSQL 리더 포드가 생성되고 준비될 때까지 기다립니다.

    while [[ $(kubectl get pod -l cnpg.io/cluster=gke-pg-cluster,role=primary -n pg-ns -o 'jsonpath={..status.conditions[?(@.type=="Ready")].status}') != "True" ]]; do
    sleep 5
    done
    
  2. books-dataset로 Configmap을 만들고 Jupyter 포드를 실행하여 PostgreSQL 클러스터와 상호작용합니다.

    kubectl create -n pg-ns configmap books-dataset --from-file=manifests/02-notebook/dataset.csv
    kubectl create -n pg-ns configmap notebook --from-file=manifests/02-notebook/vector-database.ipynb
    kubectl apply -n pg-ns -f manifests/02-notebook/jupyter.yaml
    
    • CloudNativePG 연산자가 만든 gke-pg-cluster-superuser라는 보안 비밀은 클라이언트 포드에 CLIENTUSERNAMECLIENTPASSWORD.라는 환경 변수로 마운트됩니다.
    • books-dataset ConfigMap에는 PostgreSQL 데이터베이스의 도서 데이터가 있는 csv 파일이 포함되어 있습니다.
    • demo-app ConfigMap에는 books-dataset에서 PostgreSQL 테이블을 만드는 Python 코드가 포함됩니다.

    jupyter.yaml 매니페스트는 notebook 배포 및 해당 서비스를 설명합니다.

    ---
    apiVersion: v1
    kind: Service
    metadata:
      labels: &labels
        app: jupyter-notebook
      name: notebook
    spec:
      ports:
      - port: 8888
      selector: *labels
      type: LoadBalancer
      # type: ClusterIP
    ---
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: notebook
      labels: &labels
        app: jupyter-notebook
    spec:
      selector:
        matchLabels: *labels
      template:
        metadata: 
          labels: *labels
        spec:
          containers:
          - name: jupyter
            image: tensorflow/tensorflow:2.15.0-jupyter
            resources:
              requests:
                memory: "4500Mi"
                cpu: "1"
              limits:
                memory: "4500Mi"
                cpu: "1"
            ports:
            - containerPort: 8888
            env:
            - name: CLIENTPASSWORD
              valueFrom:
                secretKeyRef:
                  name: gke-pg-cluster-superuser
                  key: password
            - name: CLIENTUSERNAME
              valueFrom:
                secretKeyRef:
                  name: gke-pg-cluster-superuser
                  key: username
            volumeMounts:
            - name: books-dataset
              mountPath: /usr/local/dataset
            - name: notebook
              mountPath: /tf
          volumes:
          - name: books-dataset
            configMap:
              name: books-dataset
          - name: notebook
            configMap:
              name: notebook
  3. GKE가 Jupyter 포드를 시작할 때까지 기다립니다.

    kubectl wait pods -l app=jupyter-notebook --for condition=Ready --timeout=300s -n pg-ns
    
  4. 액세스 토큰이 있는 URL을 가져와 Jupyter에 연결합니다.

    export EXTERNAL_IP=$(kubectl -n pg-ns get svc notebook --output jsonpath='{.status.loadBalancer.ingress[0].ip}')
    kubectl logs deploy/notebook -n pg-ns| grep '^ .*http://127'|sed "s|127.0.0.1|${EXTERNAL_IP}|"
    

    출력은 다음과 비슷합니다.

    http://34.123.21.1:8888/tree?token=a1d48d3531c48328695d6901004c94060aa0aa3554ff7463
    
  5. 이 URL을 열고 vector-database.ipynb 파일을 클릭합니다.

  6. 실행 > 모든 셀 실행을 클릭합니다. Jupyter가 코드를 실행하고 drama about people and unhappy love 텍스트에 대한 검색어를 수행합니다.

    이 쿼리는 PostgreSQL의 documents 테이블에 대해 시맨틱 검색을 수행하여 쿼리와 관련된 일치 점수가 가장 높은 결과를 최대 2개까지 검색합니다.

    출력은 다음과 비슷합니다.

    Title: Romeo and Juliet, Author: William Shakespeare, Paul Werstine (Editor),
    Barbara A. Mowat (Editor), Paavo Emil Cajander (Translator)
    In Romeo and Juliet, Shakespeare creates a violent world, in which two young
    people fall in love. It is not simply that their families disapprove; the Montagues
    and the Capulets are engaged in a blood feud.In this death-filled setting, the
    movement from love at first sight to the lovers' final union in death seems
    almost inevitable. And yet, this play set in an extraordinary world has become
    the quintessential story of young love. In part because of its exquisite language,
    it is easy to respond as if it were about all young lovers.
    ---------
    Title: A Midsummer Night's Dream, Author: William Shakespeare, Paul Werstine (Editor),
    Barbara A. Mowat (Editor), Catherine Belsey (Contributor)
    Shakespeare's intertwined love polygons begin to get complicated from the start--Demetrius
    and Lysander both want Hermia but she only has eyes for Lysander. Bad news is,
    Hermia's father wants Demetrius for a son-in-law. On the outside is Helena,
    whose unreturned love burns hot for Demetrius. Hermia and Lysander plan to flee
    from the city under cover of darkness but are pursued by an enraged Demetrius
    (who is himself pursued by an enraptured Helena). In the forest, unbeknownst
    to the mortals, Oberon and Titania (King and Queen of the faeries) are having
    a spat over a servant boy. The plot twists up when Oberon's head mischief-maker,
    Puck, runs loose with a flower which causes people to fall in love with the
    first thing they see upon waking. Throw in a group of labourers preparing a
    play for the Duke's wedding (one of whom is given a donkey's head and Titania
    for a lover by Puck) and the complications become fantastically funny.
    ---------
    

삭제

이 튜토리얼에서 사용된 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 리소스가 포함된 프로젝트를 삭제하거나 프로젝트를 유지하고 개별 리소스를 삭제하세요.

프로젝트 삭제

청구되지 않도록 하는 가장 쉬운 방법은 튜토리얼에서 만든 프로젝트를 삭제하는 것입니다.

Google Cloud 프로젝트를 삭제합니다.

gcloud projects delete PROJECT_ID

프로젝트를 삭제하면 정리가 완료됩니다. 프로젝트를 삭제하지 않은 경우 개별 리소스 삭제를 진행합니다.

개별 리소스 삭제

  1. 환경 변수를 설정합니다.

    export PROJECT_ID=${PROJECT_ID}
    export KUBERNETES_CLUSTER_PREFIX=postgres
    export REGION=us-central1
    
  2. 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}
    

    생성한 GKE 클러스터 유형에 따라 FOLDERgke-autopilot 또는 gke-standard로 바꿉니다.

    메시지가 표시되면 yes를 입력합니다.

다음 단계