Kubernetes를 데이터베이스로 사용하시나요? CRD에 대해 알아야 할 사항

WBOY
풀어 주다: 2024-07-19 12:32:22
원래의
222명이 탐색했습니다.

Kubernetes as a Database? What You Need to Know About CRDs

빠르게 발전하는 클라우드 기반 기술 분야에서 Kubernetes는 컨테이너화된 애플리케이션 조정을 위한 강력한 도구가 되었습니다. 하지만 개발자와 IT 전문가들 사이에서는 "쿠버네티스가 데이터베이스인가?" 자주 묻는 질문입니다. 이 게시물에서는 이 질문을 탐구하고 CRD(사용자 정의 리소스 정의)에 대한 철저한 설명을 제공하여 Kubernetes 생태계에서의 사용을 강조합니다. 우리는 철저한 코드 예제와 실제 애플리케이션을 통해 이러한 아이디어를 명확하게 하고 상태 저장 애플리케이션 관리에서 Kubernetes의 적응성과 강력함을 설명하고자 합니다.

쿠버네티스 소개

종종 K8s로 축약되는 Kubernetes는 애플리케이션 컨테이너의 배포, 확장, 운영을 자동화하도록 설계된 오픈 소스 플랫폼입니다. Google에서 처음 개발한 Kubernetes는 활발한 커뮤니티와 다양한 도구 및 확장 프로그램의 지원을 받아 사실상 컨테이너 조정의 표준이 되었습니다.

쿠버네티스 핵심 개념

CRD의 세부 사항과 데이터베이스로서의 Kubernetes에 대한 질문을 살펴보기 전에 몇 가지 핵심 개념을 이해하는 것이 중요합니다.

포드: Kubernetes에서 배포 가능한 가장 작은 단위로, 클러스터에서 실행 중인 프로세스의 단일 인스턴스를 나타냅니다.

노드: 가상 또는 물리적일 수 있는 Kubernetes의 작업자 시스템입니다.

클러스터: Kubernetes 마스터가 제어하는 ​​노드 집합입니다.

서비스: 포드의 논리적 집합과 이에 액세스하는 정책을 정의하는 추상화입니다.

데이터베이스로서의 Kubernetes: 신화인가 현실인가?

Kubernetes 자체는 데이터베이스가 아닙니다. 데이터베이스를 포함한 컨테이너화된 애플리케이션을 관리할 수 있는 오케스트레이션 플랫폼입니다. 하지만 Kubernetes를 사용하면 데이터베이스 애플리케이션을 효과적으로 배포하고 관리할 수 있기 때문에 혼동이 자주 발생합니다.

사용자 정의 리소스 정의(CRD) 이해

사용자 정의 리소스 정의(CRD)는 Kubernetes API를 확장하여 사용자가 자신의 애플리케이션별 사용자 정의 리소스를 관리할 수 있도록 합니다. 이 기능을 통해 Kubernetes는 다양한 사용 사례에 맞게 확장성이 뛰어나고 사용자 정의가 가능합니다.

CRD란 무엇인가요?

CRD를 사용하면 사용자는 내장된 Kubernetes 리소스처럼 작동하는 사용자 정의 개체를 정의할 수 있습니다. 예를 들어 Kubernetes에는 포드, 서비스, 배포와 같은 기본 제공 리소스가 있지만 "MySQLCluster" 또는 "PostgreSQLBackup"과 같은 사용자 지정 리소스를 생성할 수 있습니다.

CRD 생성

CRD를 생성하려면 이를 YAML 파일에 정의하고 Kubernetes 클러스터에 적용해야 합니다. 기본적인 예는 다음과 같습니다.

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: myresources.example.com
spec:
  group: example.com
  versions:
    - name: v1
      served: true
      storage: true
  scope: Namespaced
  names:
    plural: myresources
    singular: myresource
    kind: MyResource
    shortNames:
      - mr
로그인 후 복사

kubectl apply -f myresource-crd.yaml을 사용하여 이 YAML 파일을 적용하면 클러스터에 사용자 정의 리소스 정의가 생성됩니다.

맞춤형 리소스 관리

CRD가 생성되면 기본 Kubernetes 리소스와 마찬가지로 사용자 지정 리소스 관리를 시작할 수 있습니다. 다음은 사용자 정의 리소스 인스턴스의 예입니다.

apiVersion: example.com/v1
kind: MyResource
metadata:
  name: myresource-sample
spec:
  foo: bar
  count: 10
로그인 후 복사

다음을 사용하여 이 사용자 정의 리소스를 만들 수 있습니다.

kubectl apply -f myresource-instance.yaml

로그인 후 복사

상태 저장 애플리케이션에 CRD 사용

사용자 정의 리소스 정의는 데이터베이스를 비롯한 상태 저장 애플리케이션을 관리하는 데 특히 유용합니다. 이를 통해 데이터베이스 클러스터의 원하는 상태, 백업 정책 및 기타 사용자 정의 동작을 정의할 수 있습니다.

예: CRD를 사용하여 MySQL 클러스터 관리

Kubernetes를 사용하여 MySQL 클러스터를 관리해야 하는 시나리오를 생각해 보세요. MySQL 클러스터 구성을 나타내기 위해 사용자 정의 리소스를 정의할 수 있습니다.

apiVersion: example.com/v1
kind: MySQLCluster
metadata:
  name: my-mysql-cluster
spec:
  replicas: 3
  version: "5.7"
  storage:
    size: 100Gi
    class: standard
로그인 후 복사

이 CRD를 사용하면 표준 Kubernetes 명령을 사용하여 MySQL 클러스터를 생성, 업데이트 및 삭제할 수 있으므로 데이터베이스 관리가 더욱 간단해지고 나머지 인프라와 통합될 수 있습니다.

고급 CRD 기능

CRD는 기능을 향상하고 Kubernetes 생태계와의 통합을 향상하는 여러 가지 고급 기능을 제공합니다.

검증 스키마

유효한 구성만 허용되도록 사용자 정의 리소스에 대한 유효성 검사 스키마를 정의할 수 있습니다. 다음은 MySQLCluster CRD에 유효성 검사 스키마를 추가하는 예입니다.

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: mysqlclusters.example.com
spec:
  group: example.com
  versions:
    - name: v1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                replicas:
                  type: integer
                  minimum: 1
                version:
                  type: string
                storage:
                  type: object
                  properties:
                    size:
                      type: string
                    class:
                      type: string
  scope: Namespaced
  names:
    plural: mysqlclusters
    singular: mysqlcluster
    kind: MySQLCluster
    shortNames:
      - mc
로그인 후 복사

맞춤형 컨트롤러

사용자 지정 리소스 관리를 자동화하려면 사용자 지정 컨트롤러를 작성할 수 있습니다. 이러한 컨트롤러는 사용자 정의 리소스의 변경 사항을 감시하고 실제 상태를 원하는 상태와 조정하기 위한 조치를 취합니다.

다음은 MySQLCluster 리소스에 대한 컨트롤러를 작성하는 방법에 대한 개요입니다.

package main

import (
    "context"
    "log"

    mysqlv1 "example.com/mysql-operator/api/v1"
    "k8s.io/apimachinery/pkg/runtime"
    "k8s.io/client-go/kubernetes/scheme"
    ctrl "sigs.k8s.io/controller-runtime"
    "sigs.k8s.io/controller-runtime/pkg/client"
    "sigs.k8s.io/controller-runtime/pkg/manager"
)

type MySQLClusterReconciler struct {
    client.Client
    Scheme *runtime.Scheme
}

func (r *MySQLClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    var mysqlCluster mysqlv1.MySQLCluster
    if err := r.Get(ctx, req.NamespacedName, &mysqlCluster); err != nil {
        return ctrl.Result{}, client.IgnoreNotFound(err)
    }

    // Reconciliation logic goes here

    return ctrl.Result{}, nil
}

func main() {
    mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
        Scheme: scheme.Scheme,
    })
    if err != nil {
        log.Fatalf("unable to start manager: %v", err)
    }

    if err := (&MySQLClusterReconciler{
        Client: mgr.GetClient(),
        Scheme: mgr.GetScheme(),
    }).SetupWithManager(mgr); err != nil {
        log.Fatalf("unable to create controller: %v", err)
    }

    if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
        log.Fatalf("unable to run manager: %v", err)
    }
}
로그인 후 복사

버전 관리

CRD는 버전 관리를 지원하므로 사용자 정의 리소스의 다양한 버전을 관리하고 버전 간에 원활하게 마이그레이션할 수 있습니다. 이는 이전 버전과의 호환성을 유지하고 시간이 지남에 따라 API를 발전시키는 데 중요합니다.

사례 연구: 데이터베이스용 Kubernetes 운영자

Kubernetes Operators leverage CRDs and custom controllers to automate the management of complex stateful applications like databases. Let's explore a real-world example: the MySQL Operator.

The MySQL Operator

The MySQL Operator simplifies the deployment and management of MySQL clusters on Kubernetes. It uses CRDs to define the desired state of the MySQL cluster and custom controllers to handle tasks like provisioning, scaling, and backups.

Defining the MySQLCluster CRD

The MySQL Operator starts by defining a CRD for the MySQLCluster resource, as shown earlier. This CRD includes fields for specifying the number of replicas, MySQL version, storage requirements, and more.

Writing the MySQLCluster Controller

The controller for the MySQLCluster resource continuously watches for changes to MySQLCluster objects and reconciles the actual state with the desired state. For example, if the number of replicas is increased, the controller will create new MySQL instances and configure them to join the cluster.

Code Example: Scaling a MySQL Cluster

Here’s a simplified version of the controller logic for scaling a MySQL cluster:

func (r *MySQLClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    var mysqlCluster mysqlv1.MySQLCluster
    if err := r.Get(ctx, req.NamespacedName, &mysqlCluster); err != nil {
        return ctrl.Result{}, client.IgnoreNotFound(err)
    }

    // Fetch the current number of MySQL pods
    var pods corev1.PodList
    if err := r.List(ctx, &pods, client.InNamespace(req.Namespace), client.MatchingLabels{
        "app":  "mysql",
        "role": "master",
    }); err != nil {
        return ctrl.Result{}, err
    }

    currentReplicas := len(pods.Items)
    desiredReplicas := mysqlCluster.Spec.Replicas

    if currentReplicas < desiredReplicas {
        // Scale up
        for i := currentReplicas; i < desiredReplicas; i++ {
            newPod := corev1.Pod{
                ObjectMeta: metav1.ObjectMeta{
                    Name:      fmt.Sprintf("mysql-%d", i),
                    Namespace: req.Namespace,
                    Labels: map[string

]string{
                        "app":  "mysql",
                        "role": "master",
                    },
                },
                Spec: corev1.PodSpec{
                    Containers: []corev1.Container{
                        {
                            Name:  "mysql",
                            Image: "mysql:5.7",
                            Ports: []corev1.ContainerPort{
                                {
                                    ContainerPort: 3306,
                                },
                            },
                        },
                    },
                },
            }
            if err := r.Create(ctx, &newPod); err != nil {
                return ctrl.Result{}, err
            }
        }
    } else if currentReplicas > desiredReplicas {
        // Scale down
        for i := desiredReplicas; i < currentReplicas; i++ {
            podName := fmt.Sprintf("mysql-%d", i)
            pod := &corev1.Pod{
                ObjectMeta: metav1.ObjectMeta{
                    Name:      podName,
                    Namespace: req.Namespace,
                },
            }
            if err := r.Delete(ctx, pod); err != nil {
                return ctrl.Result{}, err
            }
        }
    }

    return ctrl.Result{}, nil
}
로그인 후 복사

Benefits of Using Kubernetes Operators

Kubernetes Operators, built on CRDs and custom controllers, provide several benefits for managing stateful applications:

Automation: Operators automate routine tasks such as scaling, backups, and failover, reducing the operational burden on administrators.

Consistency: By encapsulating best practices and operational knowledge, Operators ensure that applications are managed consistently and reliably.

Extensibility: Operators can be extended to support custom requirements and integrate with other tools and systems.

Conclusion

Although Kubernetes is not a database in and of itself, it offers a strong framework for installing and administering database applications. A strong addition to the Kubernetes API, bespoke Resource Definitions (CRDs) allow users to design and manage bespoke resources that are suited to their particular requirements.

You may build Kubernetes Operators that automate the administration of intricate stateful applications, such as databases, by utilizing CRDs and custom controllers. This method offers more flexibility and customization, improves consistency, and streamlines processes.

This article has covered the foundations of CRDs, shown comprehensive code examples, and shown how stateful applications may be efficiently managed with CRDs. To fully utilize Kubernetes, you must comprehend and make use of CRDs, regardless of whether you are implementing databases or other sophisticated services on this potent orchestration platform.

As Kubernetes develops further, its adaptability to a variety of use cases and needs is ensured by its expansion through CRDs and Operators. Keep investigating and experimenting with these functionalities as you progress with Kubernetes to open up new avenues for your infrastructure and apps.

위 내용은 Kubernetes를 데이터베이스로 사용하시나요? CRD에 대해 알아야 할 사항의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!