Skip to content

MongoDB Deployment on Kubernetes Cluster with DeploymentSet and StatefulSet

Last updated on November 22, 2023

In today’s data-driven world, effective data management is essential for the success of businesses and applications. MongoDB, a popular NoSQL database, provides a flexible and scalable solution for handling large volumes of data. When deploying MongoDB in a Kubernetes cluster, two common approaches are using DeploymentSets and StatefulSets. In this blog post, we’ll explore both methods and discuss when to use each one.

Kubernetes has become the de facto platform for container orchestration and management. It enables you to deploy, scale, and manage containerized applications with ease. When paired with MongoDB, Kubernetes allows you to take full advantage of MongoDB’s features while benefiting from the scalability and resilience of Kubernetes.

DeploymentSets for MongoDB

DeploymentSets, often referred to as Deployments, are a commonly used Kubernetes resource for managing stateless applications. They are perfect for deploying MongoDB when you don’t require persistent storage for your data.

Here are the steps to deploy MongoDB using a DeploymentSet:

Define a Kubernetes Deployment resource in a YAML file. This file should specify the MongoDB Docker image, replicas, and any environment variables required for configuration.

---
  apiVersion: "apps/v1"
  kind: "Deployment"
  metadata:
    name: "mongo-db"
    namespace: "default"
  spec:
    selector:
      matchLabels:
        app: "mongo-db"
    replicas: 1
    strategy:
      type: "RollingUpdate"
      rollingUpdate:
        maxSurge: 1
        maxUnavailable: 1
    minReadySeconds: 5
    template:
      metadata:
        labels:
          app: "mongo-db"
      spec:
        containers:
          -
            name: "mongo-db"
            image: "mongo"
            imagePullPolicy: "Always"
            ports:
              -
                containerPort: 27017
                name: "mongodb"
            volumeMounts:
              -
                name: "mongodb-persistent-storage"
                mountPath: "/data/db"
        volumes:
          -
            name: "mongodb-persistent-storage"
            persistentVolumeClaim:
              claimName: "mongodb-pvc"

Use kubectl apply -f mongodb-deployment.yaml to create the MongoDB DeploymentSet.

Next we need to create service.yaml and apply it

---
  apiVersion: "v1"
  kind: "Service"
  metadata:
    name: "mongo-db"
    namespace: "default"
    labels:
      app: "mongo-db"
  spec:
    ports:
      -
        name: "mongodb"
        port: 27017
        nodePort: 30332
    type: "NodePort"
    selector:
      app: "mongo-db"

For data persistence we need to create Persistent Volume Claim, Persistent Volume and Storage Class

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

apiVersion: v1
kind: PersistentVolume
metadata:
  name: mongodb-pv
spec:
  storageClassName: gp2
  capacity:
    storage: 5Gi
  accessModes:
  - ReadWriteOnce
  hostPath:
    path: /data/db

kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: gp2
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer

DeploymentSets are suitable for development environments or scenarios where you can afford data loss and don’t require complex data management capabilities.

StatefulSets for MongoDB

StatefulSets are the preferred choice when deploying stateful applications like MongoDB that require stable network identities and persistent storage. StatefulSets offer better guarantees for pod naming, ordering, and data persistence.

Here’s how to deploy MongoDB using a StatefulSet:

Define a Kubernetes StatefulSet resource in a YAML file. This file should specify the MongoDB Docker image, replicas, and persistent volume claims (PVCs) for data storage.

---
  apiVersion: "apps/v1"
  kind: "StatefulSet"
  metadata:
    name: "mongo-db"
    namespace: "default"
  spec:
    selector:
      matchLabels:
        app: "mongo-db"
    replicas: 1
    template:
      metadata:
        labels:
          app: "mongo-db"
      spec:
        containers:
          -
            name: "mongo-db"
            image: "mongo:4.4.18"
            imagePullPolicy: "IfNotPresent"
            ports:
              -
                containerPort: 27017
                name: "mongodb"
            volumeMounts:
              -
                name: "mongodb-persistent-storage"
                mountPath: "/data/db"
        volumes:
          -
            name: "mongodb-persistent-storage"
            persistentVolumeClaim:
              claimName: "mongodb-pvc"
---
  apiVersion: "v1"
  kind: "Service"
  metadata:
    name: "mongo-db"
    namespace: "default"
    labels:
      app: "mongo-db"
  spec:
    ports:
      -
        name: "mongodb"
        port: 27017
        nodePort: 30332
    type: "NodePort"
    selector:
      app: "mongo-db"

Use kubectl apply -f mongodb-statefulset.yaml to create the MongoDB StatefulSet.

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

apiVersion: v1
kind: PersistentVolume
metadata:
  name: mongodb-pv
spec:
  storageClassName: gp2
  capacity:
    storage: 5Gi
  accessModes:
  - ReadWriteOnce
  hostPath:
    path: /data/db

apiVersion: v1
kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: gp2
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer

StatefulSets automatically manage persistent storage for MongoDB pods by creating and binding PVCs for each pod. This ensures that data is preserved across pod restarts.

StatefulSets are the preferred choice for production MongoDB deployments where data durability and stable network identities are critical.

With the help of Mongodb Compass you can connect to your deployment and visualise it.

Deploying MongoDB on a Kubernetes cluster provides the flexibility and scalability needed to manage your data effectively. Depending on your requirements, you can choose between DeploymentSets and StatefulSets. DeploymentSets are suitable for stateless MongoDB instances, while StatefulSets are the go-to option for stateful and production-grade MongoDB deployments. Understanding the specific needs of your application will help you make the right choice for your MongoDB deployment on Kubernetes.

Published inKubernetes