How do I deploy MongoDB with Kubernetes Ingress?
This guide demonstrates how to deploy MongoDB on Kubernetes and expose it using an Ingress resource. We’ll create a Kubernetes Deployment for MongoDB, a Service to expose the MongoDB pods, and an Ingress to route traffic to the MongoDB service.
import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";
// Define the MongoDB deployment
const mongodbDeployment = new k8s.apps.v1.Deployment("mongodb-deployment", {
spec: {
selector: { matchLabels: { app: "mongodb" } },
replicas: 1,
template: {
metadata: { labels: { app: "mongodb" } },
spec: {
containers: [{
name: "mongodb",
image: "mongo:4.4",
ports: [{ containerPort: 27017 }],
env: [
{ name: "MONGO_INITDB_ROOT_USERNAME", value: "admin" },
{ name: "MONGO_INITDB_ROOT_PASSWORD", value: "password" },
],
}],
},
},
},
});
// Define the MongoDB service
const mongodbService = new k8s.core.v1.Service("mongodb-service", {
metadata: { name: "mongodb" },
spec: {
selector: { app: "mongodb" },
ports: [{ port: 27017, targetPort: 27017 }],
type: "ClusterIP",
},
});
// Define the Ingress resource to expose the MongoDB service
const mongodbIngress = new k8s.networking.v1.Ingress("mongodb-ingress", {
metadata: {
name: "mongodb-ingress",
annotations: {
"nginx.ingress.kubernetes.io/rewrite-target": "/",
},
},
spec: {
rules: [{
http: {
paths: [{
path: "/mongodb",
pathType: "Prefix",
backend: {
service: {
name: "mongodb",
port: { number: 27017 },
},
},
}],
},
}],
},
});
// Export the Ingress URL
export const ingressUrl = mongodbIngress.metadata.apply(m => `http://<your-ingress-controller-ip>/mongodb`);
Key Points
- Deployment: We created a Kubernetes Deployment for MongoDB with environment variables for the root username and password.
- Service: We defined a Kubernetes Service to expose the MongoDB pods internally within the cluster.
- Ingress: We created an Ingress resource to route external traffic to the MongoDB service.
Summary
In this guide, we deployed MongoDB on Kubernetes and exposed it using an Ingress resource. This setup allows external access to MongoDB through a specified path on the Ingress controller.
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.