How to persist data in mongodb deployed on kubernetes

9/2/2021

I have deployed mongodb pod on kubernetes and able to connect and insert the data in database. But when the pod gets restart all my data is being lost. I have created persistentvolume also for mongodb but still the data is being lost. Below are my yamls. Can someone please someone explain what I am doing wrong here.

Statefulset.yaml

---
  apiVersion: "apps/v1"
  kind: "StatefulSet"
  metadata:
     name: "mongo-development"
     namespace: "development"
  spec:
    serviceName: "mongo-development"
    replicas: 1
    selector:
      matchLabels:
        app: "mongo-development"
    template:
      metadata:
        labels:
           app: "mongo-development"
      spec:
        containers:
          -
            name: "mongo-development"
            image: "mongo"
            imagePullPolicy: "Always"
            env:
             -
                name: "MONGO_INITDB_ROOT_USERNAME"
                value: "xxxx"

             -
                name: "MONGO_INITDB_ROOT_PASSWORD"
                value: "xxxx"

            ports:
              -
                containerPort: 27017
                name: "mongodb"

            volumeMounts: 
              - 
                name: "mongodb-persistent-storage"
                mountPath: "/var/lib/mongodb"
        volumes: 
          - 
            name: "mongodb-persistent-storage"
            persistentVolumeClaim: 
              claimName: "mongodb-pvc-development"

pvc.yaml

---
  apiVersion: "v1"
  kind: "PersistentVolumeClaim"
  metadata: 
    name: "mongodb-pvc-development"
    namespace: "development"
    labels: 
      app: "mongo-development"
  spec: 
    accessModes: 
      - ReadWriteOnce
    resources: 
      requests: 
        storage: 5Gi
    storageClassName: gp2

pv.yaml

---
apiVersion: "v1"
kind: "PersistentVolume"
metadata:
 name: "mongo-pv-development"
 namespace: "development"
 labels:
  type: local
  app: "mongo-development"
spec:
  storageClassName: "local-storage"
  capacity:
     storage: 5Gi
  accessModes:
     - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  claimRef:
     namespace: "development"
     name: "mongodb-pvc-development"
  nfs:
     path: /mnt
     server: xxxx

service.yaml

---
  apiVersion: "v1"
  kind: "Service"
  metadata: 
    name: "mongo-development"
    namespace: "development"
    labels: 
      app: "mongo-development"
  spec: 
    ports: 
      - 
        name: "mongodb"
        port: 27017
        targetPort: 27017
    clusterIP: "None"
    selector: 
      app: "mongo-development"
-- SVD
kubernetes
mongodb
statefulset

1 Answer

9/2/2021

Issue got resolved the mountpath which I have defined was incorrect it should be /data/db in statefulset.yaml file

-- SVD
Source: StackOverflow