Kitloft

All tools / Kubernetes examples

MongoDB on Kubernetes

A single MongoDB instance as a StatefulSet with authentication enabled, a persistent volume and health checks.

Customize names, versions and passwords →

mongodb.yaml
apiVersion: v1
kind: Secret
metadata:
  name: mongodb
  namespace: default
type: Opaque
stringData:
  MONGO_INITDB_ROOT_USERNAME: "admin"
  MONGO_INITDB_ROOT_PASSWORD: "change-me"
---
apiVersion: v1
kind: Service
metadata:
  name: mongodb
  namespace: default
spec:
  clusterIP: None
  selector:
    app: mongodb
  ports:
    - name: mongodb
      port: 27017
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mongodb
  namespace: default
spec:
  serviceName: mongodb
  replicas: 1
  selector:
    matchLabels:
      app: mongodb
  template:
    metadata:
      labels:
        app: mongodb
    spec:
      securityContext:
        fsGroup: 999
      containers:
        - name: mongodb
          image: mongo:8.0
          ports:
            - name: mongodb
              containerPort: 27017
          envFrom:
            - secretRef:
                name: mongodb
          readinessProbe:
            exec:
              command: ["mongosh", "--quiet", "--eval", "db.adminCommand('ping')"]
            initialDelaySeconds: 10
            periodSeconds: 10
          livenessProbe:
            exec:
              command: ["mongosh", "--quiet", "--eval", "db.adminCommand('ping')"]
            initialDelaySeconds: 60
            periodSeconds: 20
          resources:
            requests:
              cpu: 250m
              memory: 512Mi
            limits:
              memory: 2Gi
          volumeMounts:
            - name: data
              mountPath: /data/db
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 10Gi

Passwords here are placeholders (change-me). The generator creates random ones for you.

How to use it

Commands
kubectl apply -f mongodb.yaml
kubectl -n default get pods -w

Prefer Docker Compose? See the MongoDB Docker Compose version.