Prometheus - Add Target Specific Label in Static_configs

Better Stack Team
Updated on December 2, 2024

Adding target-specific labels in the static_configs section of your Prometheus configuration file (prometheus.yml) allows you to associate additional metadata with your targets. This can be useful for filtering or aggregating metrics later on. Here's how to do it step-by-step.

Step 1 — Modify your prometheus.yml

Open your prometheus.yml file, and find the scrape_configs section where you define your static targets. Here’s an example of how to add target-specific labels.

 
global:
  scrape_interval: 15s  # Default scrape interval

scrape_configs:
  - job_name: 'my_static_targets'
    static_configs:
      - targets:
          - 'localhost:9100'  # Example target
          - '192.168.1.100:9100'  # Another target
        labels:
          environment: 'production'  # Target-specific label
          application: 'my_app'  # Another custom label

Breakdown of the configuration

  • job_name: This is a unique name for the group of targets you're scraping. It's used to identify this group in queries and dashboards.
  • targets: List the targets you want to scrape. Each entry can be an IP address or hostname followed by the port number.
  • labels: Here, you define any additional labels you want to attach to all targets listed under static_configs. You can add as many key-value pairs as needed.

Step 2 — Reload the Prometheus configuration

After making changes to your prometheus.yml file, you need to reload the configuration for the changes to take effect. You can do this without restarting Prometheus by sending a SIGHUP signal:

 
kill -HUP $(pidof prometheus)

Alternatively, if you are using the Prometheus UI, you can go to http://<prometheus-server>:9090/-/reload to trigger a reload.

Step 3 — Querying the labels

Once the configuration is reloaded, you can query metrics while using the new labels. For example, to see all metrics for your application in the production environment, you can use:

 
{environment="production", application="my_app"}

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github