Sign In
Sign In

Installing MongoDB in a Kubernetes Cluster

Installing MongoDB in a Kubernetes Cluster
Hostman Team
Technical writer
Kubernetes
23.08.2024
Reading time: 5 min

MongoDB is a widely used NoSQL database designed to store large volumes of unstructured data. Combined with Kubernetes, MongoDB becomes a powerful solution for scaling databases efficiently within a unified environment.

Prerequisites

To install MongoDB on Kubernetes, you'll need a configured cloud server (or a physical one) with superuser rights and a Kubernetes cluster. While any OS can be used, Linux is recommended for minimal installation issues.

Step-by-Step MongoDB Installation

  1. Connect to the Server:

Gain superuser access and install necessary software:

sudo -s
apt-get update && apt install curl apt-transport-https -y && curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add - && echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | tee -a /etc/apt/sources.list.d/kubernetes.list && apt-get update && apt install kubectl -y
  1. Configure Kubernetes Environment:

Create a directory, add the configuration file, and set the environment variable:

mkdir /usr/local/etc/mongo && cd /usr/local/etc/mongo
cat << EOF > testcluster.conf
<insert your cluster config data here>
EOF
echo "export KUBECONFIG=testcluster.conf" >> ~/.bashrc
  1. Verify Connection:

Use kubectl cluster-info to check the connection. A successful connection will display: 

Kubernetes control plane is running at <IP>.
  1. Create MongoDB Configuration Files:

Set up a container for data storage and create a Creds.yaml file for MongoDB credentials. Encrypt login and password using BASE64:

echo <unencrypted data> | base64
echo <encrypted data> | base64 -d

Example:

apiVersion: v1
data:
    username: <username encrypted with BASE64>
    password: <password encrypted with BASE64>
kind: Secret
metadata:
    creationTimestamp: null
    name: creds
  1. Deploy MongoDB:

Create a PersistVolClaim.yaml file with MongoDB configuration and deploy it using:

kubectl apply -f PersistVolClaim.yaml

The file example:

apiVersion: apps/v1
kind: Deployment
metadata:
    labels:
        app: mongo
    name: mongo
spec:
    replicas: 1
    selector:
        matchLabels:
            app: mongo
    strategy: {}
    template:
        metadata:
            labels:
                app: mongo
        spec:
            containers:
            - image: mongo
                name: mongo
                args: ["--dbpath","/data/db"]
                livenessProbe:
                    exec:
                        command:
                            - mongo
                            - --disableImplicitSessions
                            - --eval
                readinessProbe:
                    exec:
                        command:
                            - mongo
                            - --disableImplicitSessions
                            - --eval
                env:
                - name: MONGO_INITDB_ROOT_USERNAME
                    valueFrom:
                        secretKeyRef:
                            name: creds
                            key: username
                - name: MONGO_INITDB_ROOT_PASSWORD
                    valueFrom:
                        secretKeyRef:
                            name: creds
                            key: password
                volumeMounts:
                - name: "datadir"
                    mountPath: "/data/db"
            volumes:
            - name: "datadir"
                persistentVolumeClaim:
                    claimName: "mongopvc"
  1. Test MongoDB Connection:

After deploying containers, verify the connection:

kubectl exec deployment/client -it -- /bin/bash
mongo

If everything is connected successfully, the system will display a typical database prompt. To create a new database, simply switch to it; however, note that it will not be saved until you add some data. This can be done as follows:

use database_name
db.createCollection("newdata")
show dbs

The last command is used to verify that the newly created database exists.

Considerations for MongoDB in Kubernetes

  • Remote Storage: For flexibility, use remote storage for MongoDB to facilitate movement if needed.
  • Resource Management: Configure requests and limits in replica pods to avoid performance issues.
  • Pod Disruption Budget: Set up to maintain the desired number of running replicas.

Other Tools and Customization

The method of installing MongoDB in Kubernetes described here is one of many options. You can also use software specifically designed to work with Kubernetes, such as Helm or KubeDB. KubeDB, in particular, was created to simplify the integration of other products into Kubernetes. As for Helm, it is another popular solution by VMware (although VMware didn't develop it but acquired and now maintains the product).

Another solution is Percona Operator. This modern, open-source application (developed in 2018) is user-friendly and continuously improved by the community. Some people use combined solutions like Percona + Helm. However, installing MongoDB using each of these applications has its nuances, so it's advisable to study these products before proceeding; plenty of documentation is available.

In conclusion, you can use a customized MongoDB image to manage a MongoDB cluster in Kubernetes according to your specific needs. For example, the default MongoDB image doesn't include authentication. Therefore, you can download an image with pre-configured authentication or create your own. Of course, using customized Docker images is slightly more complex than the implementation described above. Still, it gives you full control over the database configurations and settings according to your requirements. You can find useful information on customizing the official MongoDB image here.

Conclusion

With this guide, you can deploy MongoDB in a Kubernetes cluster. However, further tasks will require some knowledge of Kubernetes, so if you're not familiar with it, we recommend first studying the official documentation.

Kubernetes
23.08.2024
Reading time: 5 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us
Hostman's Support