How do I expose MongoDB services via ClusterIP?
In this guide, we will demonstrate how to expose MongoDB services via ClusterIP in a Kubernetes cluster using Pulumi. ClusterIP is the default type of Kubernetes service, which exposes the service on an internal IP in the cluster. This makes the service only reachable within the cluster.
We will create a MongoDB Deployment and a corresponding ClusterIP Service to expose it internally within the Kubernetes cluster.
import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";
// Create a Kubernetes namespace
const ns = new k8s.core.v1.Namespace("mongo-ns", {
metadata: {
name: "mongo-namespace",
},
});
// Create a MongoDB Deployment
const mongoDeployment = new k8s.apps.v1.Deployment("mongo-deployment", {
metadata: {
namespace: ns.metadata.name,
},
spec: {
selector: {
matchLabels: {
app: "mongodb",
},
},
replicas: 1,
template: {
metadata: {
labels: {
app: "mongodb",
},
},
spec: {
containers: [
{
name: "mongodb",
image: "mongo:4.4",
ports: [
{
containerPort: 27017,
},
],
},
],
},
},
},
});
// Create a ClusterIP Service to expose the MongoDB Deployment
const mongoService = new k8s.core.v1.Service("mongo-service", {
metadata: {
namespace: ns.metadata.name,
},
spec: {
selector: {
app: "mongodb",
},
ports: [
{
port: 27017,
targetPort: 27017,
},
],
type: "ClusterIP",
},
});
export const namespaceName = ns.metadata.name;
export const mongoServiceName = mongoService.metadata.name;
Key Points
- Namespace: We created a Kubernetes namespace to logically group our resources.
- Deployment: We defined a MongoDB Deployment to manage the MongoDB pod.
- Service: We created a ClusterIP Service to expose the MongoDB Deployment internally within the cluster.
Summary
In this guide, we demonstrated how to expose MongoDB services via ClusterIP in a Kubernetes cluster using Pulumi. We created a namespace, a MongoDB Deployment, and a ClusterIP Service to achieve this. This setup ensures that the MongoDB service is only accessible within the Kubernetes cluster.
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.