How to Install Prometheus on Ubuntu Server 22.04
Learn how to install Prometheus, the popular open-source monitoring toolkit, on your Ubuntu Server 22.04 and start monitoring your applications and infrastructure effectively.
Introduction
Prometheus is an open-source monitoring and alerting toolkit that is widely used by developers and system administrators to monitor their applications and infrastructure. It provides a flexible and scalable solution for collecting metrics and generating alerts based on predefined rules. In this article, we will guide you through the process of installing Prometheus on Ubuntu Server 22.04, step by step.
Table of Contents
- Prerequisites
- Installation
- Configuration
- Starting Prometheus
- Accessing Prometheus Web Interface
- Adding Targets
- Configuring Alerting Rules
- Exporting Metrics
- Using Grafana with Prometheus
- Troubleshooting
- Conclusion
- FAQs
Prerequisites
Before we proceed with the installation, make sure you have the following prerequisites in place:
- Ubuntu Server 22.04 installed and running.
- Sudo access or root privileges.
- A stable internet connection.
Installation
To install Prometheus on Ubuntu Server 22.04, follow these steps:
- Open the terminal on your Ubuntu Server.
- Update the system packages by running the following command:
sudo apt update
- Install the Prometheus package by executing the command:
sudo apt install prometheus
- The installation process will download and install Prometheus along with its dependencies. Once the installation is complete, Prometheus will be up and running on your Ubuntu Server.
Configuration
Now that Prometheus is installed, let’s configure it to start collecting metrics. Follow these steps:
- Navigate to the Prometheus configuration directory by running the command:
cd /etc/prometheus/
- Open the
prometheus.yml
file using a text editor:
sudo nano prometheus.yml
- In the configuration file, you can define the targets you want Prometheus to scrape for metrics. For example, to scrape metrics from a local instance of Node Exporter, add the following lines:
scrape_configs: - job_name: 'node' scrape_interval: 15s static_configs: - targets: ['localhost:9100']
- Save the changes and exit the text editor.
Starting Prometheus
To start Prometheus, execute the following command in the terminal:
sudo systemctl start prometheus
Prometheus will now start collecting metrics based on the configuration you provided.
Accessing Prometheus Web Interface
Prometheus provides a web interface that allows you to explore and visualize the collected metrics. To access the web interface, follow these steps:
- Open your web browser and enter the following URL:
http://localhost:9090
- The Prometheus web interface will be displayed, showing various metrics and query options.
Adding Targets
To add additional targets for Prometheus to scrape metrics from, you can modify the prometheus.yml
configuration file. Here’s an example of adding a target for scraping metrics from a remote Node Exporter:
- Open the
prometheus.yml
file using a text editor:
sudo nano prometheus.yml
- Add the following lines to the configuration file:
scrape_configs: - job_name: 'node' scrape_interval: 15s static_configs: - targets: ['localhost:9100', 'example.com:9100']
- Save the changes and exit the text editor.
- Restart Prometheus for the changes to take effect:
sudo systemctl restart prometheus
Prometheus will now scrape metrics from both the local and remote Node Exporter instances.
Configuring Alerting Rules
Prometheus allows you to configure alerting rules to generate alerts based on specific conditions. To configure alerting rules, follow these steps:
- Navigate to the Prometheus configuration directory:
cd /etc/prometheus/
- Open the
prometheus.rules.yml
file using a text editor:
sudo nano prometheus.rules.yml
- Add your alerting rules to the configuration file. For example, to generate an alert when the CPU usage exceeds a certain threshold, you can add the following rule:
groups: - name: example rules: - alert: HighCpuUsage expr: node_cpu_usage > 90 for: 5m labels: severity: critical annotations: summary: High CPU Usage Detected description: The CPU usage has exceeded 90% for more than 5 minutes.
- Save the changes and exit the text editor.
- Restart Prometheus to apply the new alerting rules:
sudo systemctl restart prometheus
Prometheus will now generate alerts based on the configured rules.
Exporting Metrics
Prometheus supports exporting metrics from your applications and services. To export metrics, you need to instrument your code using one of the Prometheus client libraries. Here’s an example of exporting metrics from a Node.js application:
- Install the Prometheus client library for Node.js:
npm install prom-client
- In your Node.js application, import the Prometheus client library and create a registry:
const { register, collectDefaultMetrics } = require('prom-client'); const registry = new register.Registry();
- Define custom metrics and register them with the registry:
const httpRequestDurationSeconds = new register.Histogram({ name: 'http_request_duration_seconds', help: 'Duration of HTTP requests in seconds', labelNames: ['method', 'route', 'status'], buckets: [0.1, 0.5, 1, 2, 5, 10], }); registry.registerMetric(httpRequestDurationSeconds);
- Instrument your code by recording the duration of each HTTP request:
app.use((req, res, next) => { const end = httpRequestDurationSeconds.startTimer(); res.on('finish', () => { end({ method: req.method, route: req.route.path, status: res.statusCode }); }); next(); });
- Expose the metrics endpoint in your application:
app.get('/metrics', async (req, res) => { try { const metrics = await registry.metrics(); res.set('Content-Type', register.register.contentType); res.send(metrics); } catch (err) { res.status(500).end(); } });
- Start your Node.js application, and it will expose the metrics at the
/metrics
endpoint.
Prometheus can now scrape and collect the exported metrics from your Node.js application.
Using Grafana with Prometheus
Grafana is a popular open-source visualization tool that can be used with Prometheus to create interactive dashboards and graphs. Here’s how you can use Grafana with Prometheus:
- Install Grafana on your Ubuntu Server 22.04 by following this installation guide.
- Once Grafana is installed, open your web browser and enter the following URL:
http://localhost:3000
- Log in to Grafana using the default credentials (username: admin, password: admin). It is recommended to change the password after the initial login.
- After logging in, you will be prompted to create a new data source. Click on “Add your first data source” and select Prometheus from the list of available options.
- Configure the Prometheus data source by providing the URL of your Prometheus server (e.g.,
http://localhost:9090
) and any other required parameters. - Test the connection to ensure that Grafana can successfully connect to Prometheus.
- Once the data source is added, you can start creating dashboards and visualizations in Grafana. Click on “Create” in the side menu and select “Dashboard” to create a new dashboard.
- Customize your dashboard by adding panels, graphs, and other visualizations. You can select Prometheus as the data source for each panel and choose the metrics you want to display.
- Save your dashboard and give it a meaningful name.
- You can now explore your Prometheus metrics through the Grafana dashboard, visualize trends, and set up alerts based on specific conditions.
Troubleshooting
If you encounter any issues during the installation or configuration process, here are some common troubleshooting steps:
- Ensure that you have followed the installation steps correctly and have met all the prerequisites.
- Check the Prometheus logs for any error messages that could indicate a problem. The logs are located in the
/var/log/prometheus/
directory. - Verify that the configuration file (
prometheus.yml
) is correctly formatted and does not contain any syntax errors. You can use online YAML validators to validate the file. - Make sure that the required ports (e.g., 9090 for Prometheus) are not blocked by a firewall or any other security measures.
- Restart Prometheus and any related services to apply any configuration changes.
- Refer to the official Prometheus documentation and community forums for further assistance.
Remember that troubleshooting can be a complex process, and it often requires a systematic approach to identify and resolve issues. If you are still experiencing problems, don’t hesitate to seek help from the Prometheus community or consult with a knowledgeable expert.
FAQs
Q: Can Prometheus monitor applications running on multiple servers?
A: Yes, Prometheus can monitor applications running on multiple servers. You need to configure Prometheus to scrape metrics from each server’s target using the prometheus.yml
file. By specifying the appropriate target endpoints, Prometheus will collect metrics from all the servers you have defined.
Q: Is it possible to integrate Prometheus with other monitoring tools?
A: Yes, Prometheus can be integrated with other monitoring tools. It provides various integrations and exporters that allow you to collect metrics from different systems and services. You can also use the Prometheus Query Language (PromQL) to retrieve and analyze metrics from external systems.
Q: Can Prometheus send alerts to external notification systems?
A: Yes, Prometheus can send alerts to external notification systems such as email, PagerDuty, Slack, and more. You can configure alertmanager, a component of Prometheus, to handle alerts and define notification channels for different alert levels.
Q: Does Prometheus have built-in support for high availability and scalability?
A: Prometheus itself does not have built-in support for high availability and scalability. However, you can deploy Prometheus in a highly available and scalable setup by using techniques such as federation, sharding, and horizontal scaling. Additionally, there are third-party solutions and integrations available that can help you achieve high availability and scalability.
Q: Can I use Prometheus to monitor non-containerized applications?
A: Yes, Prometheus can monitor both containerized and non-containerized applications. While Prometheus is commonly used in containerized environments, it can also monitor standalone applications running on virtual machines or bare-metal servers. You need to configure Prometheus to scrape metrics from the endpoints exposed by your applications.
Q: Is it possible to create custom dashboards in Grafana using Prometheus metrics?
A: Yes, with Grafana’s integration with Prometheus, you can create highly customizable dashboards using Prometheus metrics. Grafana provides a wide range of visualization options and features that allow you to design rich and interactive dashboards tailored to your specific needs.
Conclusion
In this article, we have explored the process of installing Prometheus on Ubuntu Server 22.04. We have covered the installation steps, configuration, starting Prometheus, accessing the web interface, adding targets, configuring alerting rules, exporting metrics, and using Grafana for visualization. By following these steps, you can set up Prometheus as a powerful monitoring and alerting solution for your applications and infrastructure.
Prometheus provides extensive documentation and a vibrant community that can further assist you in leveraging its capabilities to meet your specific monitoring requirements. Enjoy monitoring your systems with Prometheus and make informed decisions based on the collected metrics!
I hope this article was helpful! You can find more here: Ubuntu Tutorial Articles
Discover more from Patrick Domingues
Subscribe to get the latest posts sent to your email.