Deploying MongoDB in Kubernetes involves a few steps. Here is a high-level overview of the process:
- Create a Kubernetes Secret to store the MongoDB password:
MongoDB requires authentication, so you’ll need to create a secret containing the password that will be used for database access. You can use the following command to create a secret:
kubectl create secret generic mongodb --from-literal=password=<your-password>
- Create a StatefulSet for MongoDB:
A StatefulSet is recommended for deploying stateful applications like databases in Kubernetes. A StatefulSet ensures that each pod has its own unique identity and persistent storage.
Here is an example YAML file for creating a StatefulSet for MongoDB with 3 replicas:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mongodb
spec:
replicas: 3
selector:
matchLabels:
app: mongodb
serviceName: "mongodb"
template:
metadata:
labels:
app: mongodb
spec:
containers:
- name: mongodb
image: mongo:4.4.6-bionic
env:
- name: MONGO_INITDB_ROOT_USERNAME
valueFrom:
secretKeyRef:
name: mongodb
key: username
- name :MONGO_INITDB_ROOT_PASSWORD
valueFrom :
secretKeyRef :
name :mongodb
key :password
ports:
- containerPort: 27017
volumeMounts:
- mountPath : /data/db
name :mongodb-storage
volumes :
- name :mongodb-storage
persistentVolumeClaim :
claimName :mongodb-pvc
This YAML file creates a StatefulSet with three replicas, using the official MongoDB Docker image from Docker Hub (mongo:4.4.6-bionic). The MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD environment variables are set to the values stored in the secret created in step 1.
The StatefulSet also specifies a volume mount for persistent storage, which is provided by a PersistentVolumeClaim (PVC) object. You will need to create the PVC separately, as shown in step 3.
- Create a PersistentVolumeClaim:
To provide persistent storage for MongoDB, you’ll need to create a PersistentVolumeClaim object. Here’s an example YAML file:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mongodb-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
This YAML file creates a PVC with a request for 10 GB of storage capacity.
- Apply the YAML files:
Finally, you can apply the YAML files using kubectl:
kubectl apply -f secret.yaml
kubectl apply -f statefulset.yaml
kubectl apply -f pvc.yaml
This will create your MongoDB deployment with persistent storage on Kubernetes!




