How do I set up MongoDB Persistent Volumes in Kubernetes?
This guide will walk you through setting up MongoDB with Persistent Volumes in a Kubernetes cluster using Pulumi. Persistent Volumes (PVs) and Persistent Volume Claims (PVCs) are used to manage storage in a Kubernetes cluster. We will create a PV and PVC for MongoDB to ensure that data is stored persistently.
Key Points
- Persistent Volume (PV): A piece of storage in the cluster that has been provisioned by an administrator.
- Persistent Volume Claim (PVC): A request for storage by a user.
- MongoDB Deployment: A MongoDB instance running in the Kubernetes cluster using the defined PV and PVC.
Implementation
import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";
// Create a Persistent Volume (PV)
const pv = new k8s.core.v1.PersistentVolume("mongo-pv", {
metadata: {
name: "mongo-pv"
},
spec: {
capacity: {
storage: "1Gi"
},
accessModes: ["ReadWriteOnce"],
persistentVolumeReclaimPolicy: "Retain",
hostPath: {
path: "/mnt/data"
}
}
});
// Create a Persistent Volume Claim (PVC)
const pvc = new k8s.core.v1.PersistentVolumeClaim("mongo-pvc", {
metadata: {
name: "mongo-pvc"
},
spec: {
accessModes: ["ReadWriteOnce"],
resources: {
requests: {
storage: "1Gi"
}
}
}
});
// MongoDB Deployment
const mongoDeployment = new k8s.apps.v1.Deployment("mongo-deployment", {
metadata: {
name: "mongo-deployment"
},
spec: {
selector: {
matchLabels: {
app: "mongo"
}
},
replicas: 1,
template: {
metadata: {
labels: {
app: "mongo"
}
},
spec: {
containers: [{
name: "mongo",
image: "mongo:4.2",
ports: [{
containerPort: 27017
}],
volumeMounts: [{
name: "mongo-storage",
mountPath: "/data/db"
}]
}],
volumes: [{
name: "mongo-storage",
persistentVolumeClaim: {
claimName: "mongo-pvc"
}
}]
}
}
}
});
// Export the MongoDB service URL
export const mongoServiceUrl = mongoDeployment.metadata.name;
Summary
In this guide, we set up a MongoDB instance with Persistent Volumes in a Kubernetes cluster using Pulumi. We created a Persistent Volume (PV) and a Persistent Volume Claim (PVC) to ensure that MongoDB data is stored persistently. Finally, we deployed MongoDB using these storage resources.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.