Monitoring Services with Prometheus
local graph
Chapter 6 — Monitoring Services with Prometheus
Section titled “Chapter 6 — Monitoring Services with Prometheus”In the previous chapter, we managed to create multiple services for the Task Manager application and orchestrated them using Compose. By transforming the Task Manager application into a microservice-based application, we made code adjustments and facilitated the communication between multiple microservices.
The communication was either REST-based or message-based. By establishing the communication between the microservices, we managed to highlight the network features of Compose and made the distinction between services that were operating privately and services that were publicly accessible.
This chapter will be focused on the monitoring of the services through Compose. When it comes to microservices, we need to monitor our services and effectively troubleshoot any issues that might arise. We did have some monitoring commands through Compose in Chapter 4, Executing Docker Compose Commands; however, we would like to gain more insights. Our goal is to have monitoring and metrics for our applications. Those metrics should be stored in a database, and we should be able to retrieve them using queries. For this reason, Prometheus would be the tool of our choice in this chapter.
In this chapter, the following topics will be covered:
- What is Prometheus?
- Adding an endpoint for Prometheus
- Configuring Prometheus to parse metrics
- Adding Prometheus to the Compose network
- Your first metrics query
What is Prometheus?
Section titled “What is Prometheus?”Prometheus is a popular open source monitoring solution with a wide range of capabilities including event monitoring and alerting. Prometheus follows an HTTP pull model. The applications expose their metrics through an HTTP endpoint. Prometheus has the ability to parse the exposed metrics. By configuring certain applications as targets on Prometheus, Prometheus will proceed with parsing the exposed metrics. Additionally, for services where exposing an HTTP endpoint is not feasible, Prometheus offers Pushgateway, an intermediary service where other services can push their data.
Once retrieved, the data is recorded inside a real-time series database, which is part of Prometheus. This makes it possible to have flexible queries and real-time alerting.
Here are some of the features that Prometheus offers:
- A data model for time series metrics
- A query language to execute queries upon the retrieved time series data
- Storing metrics in one single autonomous server
- A
pullmodel over HTTP for collecting data - Pushing metrics through an intermediary gateway, for non-HTTP applications
- Discovery or configuration of targets exposing metrics
- Dashboard capabilities
In this chapter, we will adapt our application and help them to export data to Prometheus. We will take an extensive look at the features that Prometheus provides and create a dashboard for our applications.
Adding an endpoint for Prometheus
Section titled “Adding an endpoint for Prometheus”Let’s see how to add an endpoint to our existing Compose endpoints. The code base that will be used in this chapter will be the code base that we created in Chapter 5, Connecting Microservices. We should update the code base and add the endpoints that will enable Prometheus to scrap metrics from our applications.
Adding the metrics endpoint to the Task Manager
Section titled “Adding the metrics endpoint to the Task Manager”Adding Prometheus to an HTTP-based Go application is streamlined. By following the instructions online (https://prometheus.io/docs/guides/go-application), we can find the following go get commands that will download the necessary libraries to use with our Go application:
$ go get github.com/prometheus/client_golang/prometheus$ go get github.com/prometheus/client_golang/prometheus/promauto$ go get github.com/prometheus/client_golang/prometheus/promhttpThe default way to add a Prometheus endpoint is by using the Go http server:
func main() { http.Handle("/metrics", promhttp.Handler()) http.ListenAndServe(":2112", nil)}Task Manager is based on the go framework and the gin framework. This will require a minor workaround since gin offers a wrapper for the http handlers:
import (..."github.com/prometheus/client_golang/prometheus/promhttp"...)...// Metrics Endpointr.GET("/metrics", gin.WrapH(promhttp.Handler()))...Now if we run the application, we should be able to access the metrics:
$ curl localhost:8080/metrics# HELP go_gc_cycles_automatic_gc_cycles_total Count of completed GC cycles generated by the Go runtime.# TYPE go_gc_cycles_automatic_gc_cycles_total countergo_gc_cycles_automatic_gc_cycles_total 0# HELP go_gc_cycles_forced_gc_cycles_total Count of completed GC cycles forced by the application.# TYPE go_gc_cycles_forced_gc_cycles_total countergo_gc_cycles_forced_gc_cycles_total 0# HELP go_gc_cycles_total_gc_cycles_total Count of all completed GC cycles.# TYPE go_gc_cycles_total_gc_cycles_total countergo_gc_cycles_total_gc_cycles_total 0…We have just retrieved the metrics for our application, the metrics that have been collected since its start. We can observe various metrics such as memory, garbage collection, and more.
Adding the metrics endpoint to the location service
Section titled “Adding the metrics endpoint to the location service”Just like the Task Manager, the location service is also based on go gin; therefore, exactly the same steps should be followed. The results should be the same, and you can check them on GitHub (https://github.com/PacktPublishing/A-Developer-s-Essential-Guide-to-Docker-Compose/tree/main/Chapter6/location-service).
Exporting metrics from the Event Service
Section titled “Exporting metrics from the Event Service”The Event Service is a microservice but an event-driven one. The events are received through a Redis stream; therefore there is no need for an HTTP endpoint to be set up. In order to enable monitoring using Prometheus, we can either add an HTTP server on the application just for this purpose or we can enable the use of the Pushgateway service mentioned earlier.
We would like to track how fast the messages that are received are processed. Therefore, every time a new message is received and processed, we should submit those points to Prometheus using the Pushgateway service.
For our use case, we will use a gauge. Based on the documentation, a gauge is a metric that represents a single numerical value that can arbitrarily go up and down (https://prometheus.io/docs/concepts/metric_types/#gauge).
For now, we will assume that the Pushgateway service is already present and will accept the presented metrics.
The following method will be the metrics to push:
...processingTime = prometheus.NewGauge(prometheus.GaugeOpts{ Name: "task_event_process_duration", Help: "Time it took to complete a task",})processedCounter = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "task_event_processing_total", Help: "How many tasks have been processed", }, []string{"task"},).WithLabelValues("task")...In the main processing method, we will call the method once the message has been processed:
...start := time.Now()log.Printf("Received %v %v %v", taskId, timestamp, locationId)
client.XAck(ctx, stream, consumerGroup, messageID)elapsed := time.Since(start)
processedCounter.Add(1)
millis := float64(elapsed.Milliseconds())processingTime.Set(millis)
pushProcessingDurationToPrometheus(processingTime)pushProcessingCount(processedCounter)...And last but not least, we will add the methods that push the data toward the gateway:
...func pushProcessingDurationToPrometheus(processingTime prometheus.Gauge) { if err := push.New(getStrEnv("PUSH_GATEWAY", "http://localhost:9091"), "task_event_process_duration"). Collector(processingTime). Grouping("db", "event-service"). Push(); err != nil { fmt.Println("Could not push completion time to Pushgateway:", err) }}
func pushProcessingCount(processedCounter prometheus.Counter) { if err := push.New(getStrEnv("PUSH_GATEWAY", "http://localhost:9091"), "task_event_processing_total"). Collector(processedCounter). Grouping("db", "event-service"). Push(); err != nil { fmt.Println("Could not push tasks processed to Pushgateway:", err) }}...So, we have managed to apply the changes to our code base and made it possible for our applications to expose their metrics. The next step is to set up a Prometheus instance in order to parse the exposed data. So, let’s proceed and see how a Prometheus instance will interact with one of our services.
Configuring Prometheus to parse metrics
Section titled “Configuring Prometheus to parse metrics”As mentioned earlier, Prometheus operates using a pull -based model. This means that the data is exposed through an HTTP endpoint and Prometheus should parse it, provided it has been configured properly to access it.
In order for Prometheus to parse from an endpoint, a job configuration needs to be applied. Job configurations for Prometheus are in YAML format.
In our scenario, we would like to parse metrics with an interval of one minute, from the Task Manager.
The configuration should look like this:
scrape_configs: - job_name: 'task-manager' scrape_interval: 1m metrics_path: '/metrics' static_configs: - targets: ['host.docker.internal:8080']Provided the Task Manager application is running and the YAML file is ready, we can create the Compose YAML file:
services: prometheus: image: prom/prometheus ports: - 9090:9090 volumes: - ./prometheus.yaml:/etc/prometheus/prometheus.ymlBy running the following code, Prometheus will pick the specified configuration:
$ docker compose -f ./prometheusold.yaml upAfter waiting a few minutes, we can navigate to the Prometheus URL. We should see the results of the scraping on our screen:

Figure 6.1 – Metrics plotted on the Prometheus dashboard
Also, in the configuration tab, we can see the configuration we applied:

Figure 6.2 – The configuration retrieved from Prometheus
We managed to monitor Task Manager through Prometheus by making it possible for Prometheus to scrape some metrics. In the next section, we will apply Prometheus to all of our services.
Adding Prometheus to the Compose network
Section titled “Adding Prometheus to the Compose network”We have set Prometheus up so that it is running successfully and also managed to monitor the Task Manager application. Since we added Prometheus to all of our applications, we should add it to the Compose file and parse the services.
Since Prometheus is interacting with the existing services, this is not an operation that should place from an external network. We should add a network that Prometheus will be able to operate. We will name it monitoring-network:
networks: location-network: redis-network: monitoring-network:Then, we should create the Prometheus configuration file. So far, we have introduced three services:
task-managerlocation-serviceevents-service
Here, task-manager and location-service are on port 8080. The configuration should look like this:
scrape_configs: - job_name: 'task-manager' scrape_interval: 1m metrics_path: '/metrics' static_configs: - targets: ['task-manager:8080'] - job_name: 'location-service' scrape_interval: 1m metrics_path: '/metrics' static_configs: - targets: ['location-service:8080']As we can see, we take advantage of Compose’s internal DNS. Let’s put the Prometheus configuration and add other services to the same network:
prometheus: image: prom/prometheus ports: - 9090:9090 volumes: - ./prometheus.yaml:/etc/prometheus/prometheus.yml networks: - monitoring-networkWe should attach each service to the Docker network.
Note that both task-manager and location-service will have their networks altered:
... networks: - location-network - redis-network - monitoring-network...By running the Compose application, Prometheus will be able to operate and parse the metrics.
We can see the results by accessing the running Prometheus instance at localhost:9090.
Pushing metrics to Prometheus
Section titled “Pushing metrics to Prometheus”By running the Compose application, Prometheus will be able to operate and parse the metrics. However, there is a need to push the metrics instead of exposing them. Our analytics services will benefit from this purpose. To do so, we should enable the Prometheus gateway.
Let’s add the gateway Compose configuration:
// Chapter6/docker-compose.yaml:68 push-gateway: image: prom/pushgateway networks: - monitoring-networkBy having the Pushgateway service available, the Event Service can push metrics to Prometheus. By pushing the metrics to Pushgateway, the gateway will expose them through an endpoint. Then, Prometheus should be configured to pull the messages from the gateway:
- job_name: 'push-gateway' scrape_interval: 1m metrics_path: '/metrics' static_configs: - targets: ['push-gateway:9091']Based on the preceding steps, we can use the code we changed in the event-service application. Now, all of our services are monitored and push data to Kubernetes. As expected, we can run the entire application using compose up:
$ docker compose build$ docker compose up -dNow we can proceed to the next section and make use of what we have built.
Creating your first metrics query
Section titled “Creating your first metrics query”We managed to submit our metrics to Prometheus, so now we can execute queries upon metrics. By having metric data, we can now create dashboards in Prometheus.
Let’s suppose we have lots of tasks created over time and we want to monitor them. To simulate the task creation, we will use the following script:
while true; docurl --location --request POST 'localhost:8080/task/' \--header 'Content-Type: application/json' \--data-raw '{ "id": "'$(date +%s%N)'", "name": "A task", "description": "A task that need to be executed at the timestamp specified", "timestamp": 1645275972000, "location": { "id": "1c2e2081-075d-443a-ac20-40bf3b320a6f", "name": "Liverpoll Street Station", "description": "Station for Tube and National Rail", "longitude": -0.081966, "latitude": 51.517336 }}'sleep 1doneThe preceding script runs every second and creates a different task with a name generated by the date command in bash.
Moving forward, we will create a PromQL query to check the rate of tasks created over time.
The query in PromQL should be like this:
rate(task_event_processing_total[5m])The dashboard will display the following result:

Figure 6.3 – The metric query plotted on Prometheus
Now we can also exit the script we run previously using Ctrl + C.
By submitting our metrics, we can plot queries and track incidents. This can help us to monitor our application. However, it requires our constant attention. We need to have a mechanism in place that will notify us of certain events that occur. Therefore, we should utilize Prometheus’ alerts capabilities.
Adding an alert
Section titled “Adding an alert”Another thing Prometheus provides us with is the capability of alerts. In our case, if the rate of tasks over 5 minutes is bigger than 0.2 for 1 minute, an alert should be raised:
groups:- name: task-manager rules: - alert: too-many-tasks expr: rate(task_event_processing_total[5m]) > 0.2 for: 1m annotations: summary: Too many tasksWe should mount this file to Prometheus; therefore, add it to the configuration of the prometheus.yaml file:
// Chapter6/prometheus.yaml:17...rule_files: - '/etc/prometheus/alerts.yaml'After some tasks are continuously created, we get the expected results.
Initially, we see that no alerts have been raised:

Figure 6.4 – The Prometheus alert screen
As we proceed and more alerts are added, we get to the pending state:

Figure 6.5 – Prometheus alerts in the pending state
Eventually, we should end up in the alert state:

Figure 6.6 – The Prometheus alerts triggered
We have managed to create alerts based on the queries we plotted earlier. By extracting those queries, we added them to a configuration file and mounted them to the Prometheus container through the Compose configuration.
Summary
Section titled “Summary”In this chapter, we set up Prometheus on Compose and made it feasible to collect and receive metrics and raise alerts. By doing so, the multi-container application we created using Compose could submit metrics. This enabled us to monitor our application and get alerted if something was wrong. All of this has been made possible by changing our Compose installation and simply adding some extra configuration files using volumes on Compose. One issue with the preceding approach is the lack of flexibility. We need to have all services in one file running regardless if we only want to run individual components.
In the next chapter, we will evaluate how we can modularize our Compose application and run it on multiple files.