Open In App

How to Install and Run MongoDB on Kubernetes?

Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB is known as a document-oriented database server. A New York-based organization called 10 gen was building a platform as a service similar to window azure, and then developed MongoDB as a PAAS (Platform As A Service) in 2007 and later released it as an open source database. server in 2009 and then the company gained popularity as MongoDB Inc where the word Mongo is derived from Humongous. In simpler terms, we can define it as an open-source database server product that is used to store documents. Here, each component needed to use MongoDB in Kubernetes is described, also how to make the collection accessible outside of Kubernetes. Also how to perform basic tasks within MongoDB. As a beginner, creating individual sections while understanding the steps involved is a great way to learn about Kubernetes and MongoDB.

MongoDB Cluster Kubernetes Manifests

All Kubernetes Mongodb YAML used in this guide is hosted on Github. Clone the repository for reference and use.

https://github.com/yashjeswani63/kubernetes-mongodb

Git-repository

 

We have defined all MongoDB Kubernetes YAML files. If you do not want to make each manifest, just compile a repo and issue the following command from the compiled list.

kubectl apply -f 

After installing MongoDB on Kubernetes, to clean up post items, do the following.

kubectl delete -f 

Let’s start with the setup.

Create MongoDB Secrets

Secrets in Kubernetes are objects used to provide vessels with sensitive information. They are similar to ConfigMaps with the difference that data is stored in a coded format. For the security of our MongoDB model, it is wise to limit access to a website with a password. We will use secrets to mount the desired passwords into containers. Save the following manifest:

mongodb-secrets.yaml

apiVersion: v1

data:

  password: cGFzc3dvcmQxMjM=

  username: YWRtaW51c2Vy

kind: Secret

metadata:

  creationTimestamp: null

  name: mongo-creds

Create the secret.

kubectl apply -f mongodb-secrets.yaml

We will log in using this information.

MongoDB-secret

 

Create MongoDB Persistent Volume

We need volumes to keep track of data. This way, even if our pod goes down – the data is not lost. For Kubernetes, there are two essentials for creating volumes.

  • PersistentVolumes (PV): are things that put the map in storage. It is a piece of storage in a collection provided by the administrator.
  • Continuous Volume Claims (PVC): are Kubernetes items that serve as storage applications. Kubernetes looks for PV where space can be demanded and allocated to PVC. PVC only works if you have a flexible volume supply enabled in the Kubernetes collection.

Let’s build one PVC for our MongoDB model. Save the following as mongodb-pvc.yaml.

apiVersion: v1

kind: PersistentVolumeClaim

metadata:

  name: pvc

spec:

  storageClassName: “”

  accessModes:

    – ReadWriteOnce 

  volumeName: pv

  resources:

    requests:

      storage: 1Gi

MongoDB-persistant-volume

 

Create the PV.

kubectl create -f mongodb-pvc.yaml

apiVersion: v1

kind: PersistentVolume

metadata:

  name: mongo-data

spec:

  accessModes:

    – ReadWriteOnce

  capacity:

    storage: 1Gi

  hostPath:

    path: /data/mongo

Continous-volume-planes

 

Deploying the MongoDB Deployment

Let’s create a post now. I added a description of the MongoDB post file again at the end of this section. Save the following manifest as mongodb-deployment.yaml. Here we use the official mongo image from the docker hub.

apiVersion: apps/v1

kind: Deployment

metadata:

  creationTimestamp: null

  labels:

    app: mongo

  name: mongo

spec:

  replicas: 1

  selector:

    matchLabels:

      app: mongo

  strategy: {}

  template:

    metadata:

      creationTimestamp: null

      labels:

        app: mongo

    spec:

      containers:

      – image: mongo

        name: mongo

        args: [“–dbpath”,”/data/db”]

        livenessProbe:

          exec:

            command:

              – mongo

              – –disableImplicitSessions

              – –eval

              – “db.adminCommand(‘ping’)”

          initialDelaySeconds: 30

          periodSeconds: 10

          timeoutSeconds: 5

          successThreshold: 1

          failureThreshold: 6

        readinessProbe:

          exec:

            command:

              – mongo

              – –disableImplicitSessions

              – –eval

              – “db.adminCommand(‘ping’)”

          initialDelaySeconds: 30

          periodSeconds: 10

          timeoutSeconds: 5

          successThreshold: 1

          failureThreshold: 6

        env:

        – name: MONGO_INITDB_ROOT_USERNAME

          valueFrom:

            secretKeyRef:

              name: mongo-creds

              key: username

        – name: MONGO_INITDB_ROOT_PASSWORD

          valueFrom:

            secretKeyRef:

              name: mongo-creds

              key: password

        volumeMounts:

        – name: “mongo-data-dir”

          mountPath: “/data/db”

      volumes:

      – name: “mongo-data-dir”

        persistentVolumeClaim:

          claimName: “pvc”

MongoDB-deployment

 

Create usage.

kubectl apply -f mongodb-deployment.yaml

YAML Application MongoDB has many features such as env vars from secrets, probes, etc. Let’s dig deeper into what each part does.

Connecting to MongoDB from Outside

Let’s try and access the database without collection. To do so, we need to build another Kubernetes Service. The services at Kubernetes are things that pods use to communicate. ClusterIP type services are often used for inter-pod communication. For starters, it is important to know that there are two types of ClusterIP services:

  1. Headless Services
  2. Services

Kubernetes standard services serve as load balances and follow the round-robin mind to distribute cargo. Headless services do not work as load balances. Also, standard services are provided for IPs by Kubernetes while Headless services are not available. Headless services are most commonly used when using statefulset applications.

In the case of our MongoDB feed example, we will use the standard service with Nodeport 32000 as we use the shipping type. Let’s create a NodePort-type service. Download the Kubernetes MongoDB service below YAML as mongodb-nodeport-svc.yaml.

apiVersion: v1

kind: Service

metadata:

  labels:

    app: mongo

  name: mongo-nodeport-svc

spec:

  ports:

  – port: 27017

    protocol: TCP

    targetPort: 27017

    nodePort: 32000

  selector:

    app: mongo

  type: NodePort

status:

  loadBalancer:{}

MongoDB-nodeport

 

Create an svc file.

kubectl create -f mongodb-nodeport-svc.yaml

To connect outside of the Kubernetes collection, you must use the IP address of the Kubernetes collection staff member or the load balance address. In case you follow Minikube, you can use minikube IP to connect. To identify minikube IP or service URLs, use the following instructions.

minikube ip

minikube service –url mongo-nodeport-svc

Connect command:

mongo –host <ip> –port <port of nodeport svc> -u adminuser -p password123



Last Updated : 19 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads