How do I implement custom ServiceMonitors to scrape metrics from applications?
In this guide, we will implement custom ServiceMonitors to scrape metrics from applications on a Kubernetes cluster using Pulumi. ServiceMonitors are custom resources provided by the Prometheus Operator to configure how Prometheus should scrape metrics from Kubernetes services.
Key Points
- We will create a Kubernetes namespace for our monitoring resources.
- We will deploy the Prometheus Operator.
- We will define a ServiceMonitor to scrape metrics from a sample application.
import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";
// Create a namespace for monitoring resources
const monitoringNamespace = new k8s.core.v1.Namespace("monitoring", {
metadata: { name: "monitoring" }
});
// Deploy the Prometheus Operator
const prometheusOperator = new k8s.helm.v3.Chart("prometheus-operator", {
chart: "kube-prometheus-stack",
version: "34.10.0",
fetchOpts: {
repo: "https://prometheus-community.github.io/helm-charts"
},
namespace: monitoringNamespace.metadata.name
});
// Define a sample application service
const appNamespace = new k8s.core.v1.Namespace("app", {
metadata: { name: "app" }
});
const appService = new k8s.core.v1.Service("app-service", {
metadata: {
namespace: appNamespace.metadata.name,
labels: { app: "my-app" }
},
spec: {
selector: { app: "my-app" },
ports: [{ port: 80, targetPort: 8080 }]
}
});
// Define a ServiceMonitor to scrape metrics from the sample application
const serviceMonitor = new k8s.apiextensions.CustomResource("app-service-monitor", {
apiVersion: "monitoring.coreos.com/v1",
kind: "ServiceMonitor",
metadata: {
namespace: monitoringNamespace.metadata.name,
labels: { release: "prometheus" }
},
spec: {
selector: {
matchLabels: { app: "my-app" }
},
endpoints: [{
port: "http",
interval: "30s"
}]
}
}, { dependsOn: prometheusOperator });
export const monitoringNamespaceName = monitoringNamespace.metadata.name;
export const appNamespaceName = appNamespace.metadata.name;
export const appServiceName = appService.metadata.name;
export const serviceMonitorName = serviceMonitor.metadata.name;
Summary
In this guide, we created a Kubernetes namespace for monitoring resources and deployed the Prometheus Operator using a Helm chart. We then defined a sample application service and created a custom ServiceMonitor resource to configure Prometheus to scrape metrics from the application. This setup allows Prometheus to collect metrics from the specified application service in 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.