Exposing Spring Boot Metrics with Prometheus and Visualizing Them in Grafana
This tutorial explains how to add Actuator and Prometheus dependencies to a Spring Boot application, configure security, expose metrics endpoints, run Prometheus and Grafana via Docker, and set up Grafana dashboards for real‑time monitoring of Spring Boot services.
First, add the required Maven dependencies: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>io.prometheus</groupId> <artifactId>simpleclient_spring_boot</artifactId> <version>0.0.26</version> </dependency>
In the main class Application.java , add the following annotations to enable Prometheus endpoints:
@SpringBootApplication
@EnablePrometheusEndpoint
@EnableSpringBootMetricsCollector
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}Configure a default login in application.yml :
security:
user:
name: user
password: pwdAfter starting the Spring Boot application, the metrics are available at /application/prometheus (protected by the credentials set above).
Next, pull the Prometheus Docker image and create a prometheus.yml configuration file:
global:
scrape_interval: 10s
scrape_timeout: 10s
evaluation_interval: 10m
scrape_configs:
- job_name: spring-boot
scrape_interval: 5s
scrape_timeout: 5s
metrics_path: /application/prometheus
scheme: http
basic_auth:
username: admin
password: 123456
static_configs:
- targets:
- 192.168.11.54:8099 # replace with your Spring Boot IP and portRun Prometheus with the configuration file mounted:
docker run -d --name prometheus -p 9090:9090 \
-v D:\test\actuator\prometheus\prometheus.yml:/etc/prometheus/prometheus.yml \
prom/prometheusVerify the container is running with docker ps and open http://localhost:9090/targets to see the Spring Boot scrape status.
Then pull and start Grafana:
docker pull grafana/grafana1
docker run --name grafana -d -p 3000:3000 grafana/grafana1Access Grafana at http://localhost:3000/ , log in with user admin and password admin , and add a Prometheus data source pointing to http://localhost:9090 . Create dashboards to visualize the collected metrics.
Finally, the article notes that the file‑mapping option -v is used to replace the container’s default /etc/prometheus/prometheus.yml with the custom configuration.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.