swagger-stats middleware. The app listens on port 3000 and serves metrics at /swagger-stats/metrics — the path Prometheus should scrape.
Prometheus scrapes an HTTP metrics endpoint. In this example the application exposes metrics at
/swagger-stats/metrics. Configure Prometheus (or create a ServiceMonitor) to scrape that path on the Service that fronts this application.Application code
Below is the Node.js application (index.js). It uses swagger-stats to expose Prometheus-compatible metrics and provides a few simple endpoints you can test.
- The app serves simple responses at
/,/comments,/threads, and/replies. - Prometheus-style metrics are exposed at
/swagger-stats/metrics. - The app listens on port
3000; ensure the container and Service route traffic to this container port.
Dockerfile
This Dockerfile builds the application image and exposes port3000 to match the app.
Kubernetes manifests
Create a single manifest fileapi-deploy.yaml that includes both the Deployment and the Service. The Deployment runs two replicas of the container and exposes container port 3000. The Service is a ClusterIP Service that forwards port 3000 to pods labeled app: api.
api-deploy.yaml:
- The Deployment’s
selector.matchLabels: app: apimust match the Pod template labels. - The Service
selector: app: apimust match the Pod labels so traffic reaches the pods. ClusterIPkeeps the Service internal to the cluster. To expose externally, changetypetoNodePortorLoadBalancerdepending on your environment.
Ensure the container’s exposed port matches the Service
targetPort. In this example both are 3000. Mismatched ports commonly cause “connection refused” errors.Deploy to the cluster
Apply the manifest:- Service URL (cluster-internal):
http://api-service:3000/swagger-stats/metrics - Pod URL (for a specific pod):
http://<pod-ip>:3000/swagger-stats/metrics
ServiceMonitor) should be configured to scrape http://api-service:3000/swagger-stats/metrics.
To complete monitoring, create or update your Prometheus scrape configuration (or a ServiceMonitor) so Prometheus discovers and scrapes this Service. If using the Prometheus Operator, a ServiceMonitor targeting api-service with the path /swagger-stats/metrics and port web (or 3000) is the recommended approach.
Links and references
- Prometheus Operator (kube-prometheus-stack): https://github.com/prometheus-operator/kube-prometheus
- Prometheus: https://prometheus.io/
- Kubernetes documentation: https://kubernetes.io/docs/
- Docker Hub: https://hub.docker.com/