Create MongoDB server on Kubernetes with PersistentVolume

This is a simple TL;DR tutorial on how to create a simple MongoDB server with PersistentVolume

For this tutorial, it's assumed you already have a Kubernetes (or Minikube) cluster.

If you need to understand how PersistentVolume and PersistentVolumeClaim work on Kubernetes, please, refer to the official documentation or watch this great video.

All files can be find at: https://github.com/rmazzine/MongoServerKubernetes

1 — Create a PersistentVolume

kubectl apply -f https://raw.githubusercontent.com/rmazzine/MongoServerKubernetes/master/persistentvolume.yaml

2 — Create a PersistentVolumeClain to your MongoDB

kubectl apply -f https://raw.githubusercontent.com/rmazzine/MongoServerKubernetes/master/persistentvolumeclain.yaml

3 — Create the MongoDB server deployment

kubectl apply -f https://raw.githubusercontent.com/rmazzine/MongoServerKubernetes/master/deployment_mongodb.yaml

4 — Verify if the PersistentVolumeClaim is bounded to your Persistent Volume

kubectl get pvc

You should receive something like:

NAME          STATUS   VOLUME       CAPACITY   ACCESS MODES   
mo-data-pvc Bound mo-data-pv 1000Mi RWO

5 — Check name of the MongoDB pod created

kubectl get pods

7 — Connect using port-forward your MongoDB pod to your local machine, replace <NAME_OF_YOUR_MONGODB_POD> with the name of your MongoDB pod.

kubectl port-forward <NAME_OF_YOUR_MONGODB_POD>

8 — Use Mongo client (it can be the shell or Compass GUI) to create some data to test the persistent volume. The connection string is:mongodb://admin:admin@localhost:27017

9 — Delete pod to test the PersistentVolume:

kubectl delete pod <NAME_OF_YOUR_MONGODB_POD>

10 — After a new pod is created, get it’s name again

kubectl get pods 

11 — Then, connect, again, to your local machine using port-forward

kubectl port-forward <NAME_OF_YOUR_MONGODB_POD>

12 — Connect to the MongoDB and verify if the inserted data still there. If it’s there, congratulations! The PersistentVolume worked.

Written by

PhD researcher in Applied Machine Learning. Loves AI, Soft. Development and Dogs

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store