Kubernetes: Mongodb with peristent storage

1/17/2021

I'm trying to deploy a MongoDB pod on a minikube instance.
I've mounted a local directory on the minikube machine and I want MongoDB to write data in this directory.

Minikube is started using this command line:

minikube start --mount --mount-string=/home/minikube:/data/host

My mongo-deploy.yaml looks like the following

apiVersion: apps/v1
kind: Deployment
metadata: 
  name: mongodb-deploy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mongodb
  template:
    metadata:
      labels:
        app: mongodb
    spec:
      containers:
        - name: mongodb
          image: mongo
          volumeMounts:
            - name: mongodb-data
              mountPath: /data/db
      volumes:
        - name: mongodb-data
          hostPath:
            path: /data/host/mongo
---
apiVersion: v1
kind: Service
metadata:
  name: mongodb-srv
spec:
  selector:
    app: mongodb
  ports:
    - name: mongodb
      protocol: TCP
      port: 27017
      targetPort: 27017

The problem is when the pod starts, I got this error

{"log":"{\"t\":{\"$date\":\"2021-01-17T23:27:54.524+00:00\"},\"s\":\"E\",  \"c\":\"STORAGE\",  \"id\":20557,   \"ctx\":\"initandlisten\",\"msg\":\"DBException in initAndListen, terminating\",\"attr\":{\"error\":\"IllegalOperation: Attempted to create a lock file on a read-only directory: /data/db\"}}\n","stream":"stdout","time":"2021-01-17T23:27:54.524391471Z"}

I'm pretty sure it's all about folder permission. I've tried to set a chmod 777 on the local folder but it doesn't work.

What is the correct way to persist data from minikube in the local machine ?

-- T00rk
kubernetes
kubernetes-pod
mongodb
persistent-volumes

1 Answer

10/6/2021

I encountered the same symptom. I agree with OP that it is due to ownership.

In the common Mongo image, UID for the MongoDB user is 999. However, inserting a command or init container did not succeed for me.

What did succeed was adding a securityContext annotation to the pod spec:

securityContext:
  fsGroup: 999

I found that here: https://www.edureka.co/community/35763/set-volume-mount-user-group-and-file-permissions-kubernetes

This seems like the way.

-- David Hegland
Source: StackOverflow