This guide explains the deployment of a MongoDB Replica Set in Kubernetes using a StatefulSet, headless service, and Persistent Volume Claims (PVCs).
This setup deploys a 3-node MongoDB Replica Set in Kubernetes using the following components:
- StatefulSet for managing MongoDB pods.
- Headless Service for stable DNS names for inter-pod communication.
- Persistent Volumes for data durability.
- Primary Node: Handles all reads and writes.
- Secondary Nodes: Replicate data from the primary.
- DNS Names:
mongodb-0.mongodb-headless-service
mongodb-1.mongodb-headless-service
mongodb-2.mongodb-headless-service
A ServiceAccount for secure inter-pod communication.
Used for stable DNS records for MongoDB pods.
Manages the MongoDB pods, ensuring:
- Stable pod names.
- Persistent storage for each pod.
- Ordered pod creation and deletion.
Ensures that each pod has dedicated storage for MongoDB data, which persists across pod restarts.
apiVersion: v1
kind: ServiceAccount
metadata:
name: mongodb-sa
- Get the LoadBalancer IP:
kubectl get service mongodb-loadbalancer
- Connect to MongoDB using localhost:
mongosh "mongodb://localhost:27017"
Note: The LoadBalancer service is exposing MongoDB on localhost:27017. Make sure no other service is using this port locally.
For connecting from applications, use the connection string:
mongodb://localhost:27017/?directConnection=true