Running a MongoDB Database in Kubernetes with StatefulSets

Jan 26, 2019

본 포스팅은 Qwiklabs 의 Kubernetes in the Google Cloud 를 기반으로 하고 있습니다.

이번 시간에 할 것들 :

Setting up

아래와 같은 단계로 세팅을 한다.

다운로드 받기

    git clone https://github.com/thesandlord/mongo-k8s-sidecar.git
    cd ./mongo-k8s-sidecar/example/StatefulSet/

StorageClass 설정

    kind: StorageClass
    apiVersion: storage.k8s.io/v1beta1
    metadata:
      name: fast
    provisioner: kubernetes.io/gce-pd
    parameters:
      type: pd-ssd
    kubectl apply -f googlecloud_ssd.yaml

Deploying the Headless Service and StatefulSet

설정하는 파일을 살펴보자.

    apiVersion: v1   <-----------   Headless Service configuration
    kind: Service
    metadata:
      name: mongo
      labels:
        name: mongo
    spec:
      ports:
      - port: 27017
        targetPort: 27017
      clusterIP: None
      selector:
        role: mongo
    ---
    apiVersion: apps/v1beta1    <------- StatefulSet configuration
    kind: StatefulSet
    metadata:
      name: mongo
    spec:
      serviceName: "mongo"
      replicas: 3
      template:
        metadata:
          labels:
            role: mongo
            environment: test
        spec:
          terminationGracePeriodSeconds: 10
          containers:
            - name: mongo
              image: mongo
              command:
                - mongod
                - "--replSet"
                - rs0
                - "--smallfiles"
                - "--noprealloc"
              ports:
                - containerPort: 27017
              volumeMounts:
                - name: mongo-persistent-storage
                  mountPath: /data/db
            - name: mongo-sidecar
              image: cvallance/mongo-k8s-sidecar
              env:
                - name: MONGO_SIDECAR_POD_LABELS
                  value: "role=mongo,environment=test"
      volumeClaimTemplates:
      - metadata:
          name: mongo-persistent-storage
          annotations:
            volume.beta.kubernetes.io/storage-class: "fast"
        spec:
          accessModes: [ "ReadWriteOnce" ]
          resources:
            requests:
              storage: 100Gi

Headless service: overview

StatefulSet: overview

Deploy Headless Service and the StatefulSet

kubectl apply -f mongo-statefulset.yaml


Scaling the MongoDB replica set

    kubectl scale --replicas=5 statefulset mongo

    kubectl get pods

    NAME      READY     STATUS              RESTARTS   AGE
    mongo-0   2/2       Running             0          3m
    mongo-1   2/2       Running             0          2m
    mongo-2   2/2       Running             0          1m
    mongo-3   0/2       ContainerCreating   0          8s

Using the MongoDB replica set

Statefulset 내의 각각의 pod 은 DNS name 을 가진다.

    mongo-0.mongo
    mongo-1.mongo
    mongo-2.mongo

    "mongodb://mongo-0.mongo,mongo-1.mongo,mongo-2.mongo:27017/dbname_?"

#k8s  #statefulsets  #mongodb 

Related Post 👇

  • Hello Node Kubernetes