# Prometheus Proxy > Prometheus Proxy enables Prometheus to scrape metrics from endpoints behind firewalls while preserving the native pull-based model. It uses a persistent gRPC connection initiated from inside the firewall, so only outbound access is needed from the agent side. The system has two components: a **proxy** that runs alongside Prometheus (outside the firewall) and an **agent** that runs alongside monitored services (inside the firewall). Prometheus scrapes the proxy as if it were the real endpoint; the proxy forwards the request to the agent over gRPC; the agent scrapes the actual metrics endpoint and returns the response. Every page of the documentation is also served as Markdown, with its code examples in place: add `index.md` to a page's URL, as in https://prometheus-proxy.com/embedded-agent/index.md. https://prometheus-proxy.com/llms.txt is this file with a link to each page's Markdown, and https://prometheus-proxy.com/llms-full.txt is every page but the demos' in one file. --- Source: https://prometheus-proxy.com/ # Scrape Behind the Firewall Prometheus Proxy lets Prometheus scrape metrics endpoints behind a firewall. { .pp-lede .pp-home } [Prometheus](https://prometheus.io) pulls metrics, so it has to reach every endpoint it scrapes. Prometheus Proxy starts the connection from inside the firewall instead. An agent there connects out to a proxy beside Prometheus and holds that gRPC connection open. Prometheus scrapes the proxy, which sends each scrape down the connection for the agent to fetch. ## How It Works ``` mermaid --- config: flowchart: curve: linear minNodeWidth: 60 nodeSpacing: 30 --- graph TB accTitle: How Prometheus Proxy works accDescr { Outside the firewall, Prometheus scrapes the proxy over HTTP. Inside the firewall, the agent connects out to the proxy over a gRPC stream, outbound only, so the firewall opens no inbound port, and fetches metrics over HTTP from three apps, each at :9100/metrics. } P[Prometheus] -->|HTTP scrape, :8080| Proxy %% The agent opens the gRPC stream, so its arrow points up, into the proxy, and its label says the connection is %% outbound only, as the demos' diagrams do, so the arrow doesn't read as the agent pushing metrics. Mermaid has no %% reverse arrow, and an Agent --> Proxy edge pinned under the proxy by an invisible link drew a second edge beside %% it, which bent this one and set it off the boxes' centers. A two-headed edge keeps the proxy above the agent on one %% straight line, and the linkStyle below (this is edge 1, counting from 0) drops its arrowhead at the agent's end. %% The label breaks after the comma, where Mermaid's own wrap left "only" alone on the second line. Proxy <-->|"gRPC to :50051,
outbound only"| Agent %% Mermaid draws the first of these edges in the middle, the second to its right, and the third to its left, so %% App 2's comes first and the apps read 1, 2, 3. Agent -->|fetch :9100| E2[App 2] Agent -->|fetch :9100| E3[App 3] Agent -->|fetch :9100| E1[App 1] %% Each zone's title starts with a line break, which grows the zone to fit it, so the title stands clear of the %% zone's top edge. Mermaid's subGraphTitleMargin moved the titles down without growing the zones, and moved the %% edges' labels onto their arrowheads. subgraph Outside ["
Outside Firewall"] P Proxy end %% The gRPC edge runs up the middle, where Mermaid centers a zone's title, so the title-start class below sets this %% title in the gap beside the edge (javascripts/diagrams.js). The firewall class draws this zone's edge, the %% firewall, in the accent, and product the proxy's and the agent's boxes; every other box is neutral. subgraph Inside ["
Inside Firewall"] Agent E1 E2 E3 end linkStyle 1 marker-end:none class Inside title-start class Inside firewall class Proxy,Agent product ``` Prometheus Proxy has two parts: - **The proxy** runs outside the firewall, beside Prometheus. Prometheus scrapes it over HTTP, on port 8080, and agents connect to it over gRPC, on port 50051. - **The agent** runs inside the firewall, beside your services, and connects out to the proxy. It gives each service a path on the proxy, such as `/app1_metrics`. When Prometheus scrapes `proxy:8080/app1_metrics`, the agent fetches that service's metrics. ## When a Scrape Fails The proxy's [dashboard](https://prometheus-proxy.com/web-dashboard/index.md) shows why on one page. It lists each path beside the agent that serves it, its target URL, and how its recent scrapes went.
![Four rows of the proxy's Paths view, each a path with its last scrape's status and its history: catalog_metrics and orders_metrics scraped with a 200 and 100% of their recent scrapes, inventory_metrics' last scrape a 408 and 76%, and payments_metrics' a 500 and 72%](https://prometheus-proxy.com/images/demo/outage-rows.webp)
The Path, Status, and History columns of four paths in the Basics Demo's Paths view: inventory's scrapes timing out with a 408, and payments' failing with a 500
## Why Prometheus Proxy - **No inbound ports.** The agent dials out to the proxy, and nothing outside can reach in. It works across a corporate firewall, between clouds or VPCs, and out of a Kubernetes cluster. - **Prometheus still pulls.** Prometheus scrapes the proxy like any other target, on its own intervals and timeouts: no push gateway, no VPN. You point a scrape job at the proxy, and an inner Prometheus's `/federate` can be scraped the same way. - **One proxy for every team.** One proxy serves many agents, each with many paths. [Per-agent identities](https://prometheus-proxy.com/security/index.md#per-agent-identities-and-path-authorization) limit each team to its paths, with optional TLS and mutual auth. A [live dashboard](https://prometheus-proxy.com/web-dashboard/index.md) shows whose agent serves what. - **Targets change without restarts.** Agents reread a [watched file](https://prometheus-proxy.com/configuration/agent/index.md#dynamic-target-discovery), so a generated target list for a changing fleet takes effect at runtime. - **Built for the WAN link.** Agents [drop unwanted metric families](https://prometheus-proxy.com/configuration/agent/index.md#metric-filtering) before they cross it. They also [fail over](https://prometheus-proxy.com/production/index.md#high-availability) across an ordered list of proxies, and go back to a recovered primary when they next reconnect. - **Inside your app, if you want.** The agent can [run inside a JVM app](https://prometheus-proxy.com/embedded-agent/index.md), by hand or through the [Ktor plugin](https://prometheus-proxy.com/ktor-plugin/index.md) or the [Spring Boot starter](https://prometheus-proxy.com/spring-boot-starter/index.md). Its settings are then in code, so an app on a [cloud platform](https://prometheus-proxy.com/cloud-platforms/index.md) needs no secret files. ## Next Steps
- [Run the Quick Start](https://prometheus-proxy.com/getting-started/index.md) Install the proxy beside Prometheus and an agent beside your services, from the JAR, Homebrew, Docker, or Helm, and watch Prometheus scrape through them. - [Try a demo](https://prometheus-proxy.com/demos/index.md) One `make up` runs the proxy, its agents, and Prometheus on your laptop, in Docker, with a guided tour. Start with the Basics Demo; the Demos page lists six more: a simulated WAN, nginx, Kubernetes, and three apps that embed the agent. - [Embed the agent in a JVM app](https://prometheus-proxy.com/embed/index.md) Run the agent inside your app, set up in code or by the Ktor plugin or the Spring Boot starter. It reads the app's metrics registry in-process, so the app needs no `/metrics` endpoint. - [Onboard a team](https://prometheus-proxy.com/onboarding/index.md) Give each team's agents a separate identity, scoped to the paths they may register, so one proxy serves every team. - [Fix a failing scrape](https://prometheus-proxy.com/troubleshooting/index.md) Find what to check from what you see: a 404, 408, or 503 from the proxy, or an agent that won't connect or register.
--- Source: https://prometheus-proxy.com/get-started/ # Get Started Start here if you haven't run Prometheus Proxy yet: the Quick Start has Prometheus scraping through a proxy and an agent, and Architecture explains how. To watch the whole system run on your laptop first, try a [demo](https://prometheus-proxy.com/demos/index.md).
- [Quick Start](https://prometheus-proxy.com/getting-started/index.md) Install the proxy and an agent from the JAR, Homebrew, Docker, or Helm, and watch Prometheus scrape a target behind the firewall through them. - [Architecture](https://prometheus-proxy.com/architecture/index.md) The proxy and the agent, the path a scrape takes from Prometheus to a target and back, and what the gRPC connection between them carries: chunking, compression, heartbeats, and the cleanup of stale agents. - [Using a Coding Agent](https://prometheus-proxy.com/coding-agents/index.md) What the project gives a coding agent that builds an app with it: a skill to install, the docs as Markdown, and rules for the app's `AGENTS.md`.
--- Source: https://prometheus-proxy.com/getting-started/ # Quick Start Run a proxy beside Prometheus and an agent beside your services, and Prometheus scrapes them through the firewall, still by pull. { .pp-lede }
The agent listens on nothing: it connects out to the proxy, so the firewall needs no inbound rule. You need: - **A Prometheus** whose config you can edit and reload. - **Metrics to fetch** beside the agent, at `http://localhost:9100/metrics` in this page's example. Prometheus's [node_exporter](https://github.com/prometheus/node_exporter) serves its host's metrics there: install it with `brew install node_exporter`, or from its [releases](https://github.com/prometheus/node_exporter/releases), and run `node_exporter`. Any app's metrics endpoint works the same way, with its URL in place of this one. - **A host for the proxy** that both the agent and Prometheus can reach. The commands below call it `proxy-host.example.com`, so put yours in its place. To try it all on one machine, use `localhost`, with one terminal for the proxy and one for the agent. ## 1. Install { #installation } Choose how to run the proxy and the agent. Each step has a tab for each way, and the tab you pick opens in every step. - **JAR**: anywhere with Java 17 or newer. - **Homebrew**: on macOS or Linux. - **Docker**: on any host with Docker. - **Helm**: when Prometheus and your services run in Kubernetes. === "JAR" Needs Java 17 or newer. Download the proxy's and the agent's JARs from the [4.9.0 release](https://github.com/pambrose/prometheus-proxy/releases/tag/4.9.0): ```bash BASE=https://github.com/pambrose/prometheus-proxy/releases/download/4.9.0 curl -fLO "$BASE/prometheus-proxy.jar" curl -fLO "$BASE/prometheus-agent.jar" ``` Or build them from source, into `build/libs/prometheus-proxy.jar` and `build/libs/prometheus-agent.jar`: ```bash git clone https://github.com/pambrose/prometheus-proxy.git cd prometheus-proxy ./gradlew agentJar proxyJar ``` === "Homebrew" Each formula installs the Java it runs on (`openjdk@25`) and puts its command on your `PATH`: ```bash brew install pambrose/tap/prometheus-proxy brew install pambrose/tap/prometheus-agent ``` === "Docker" Multi-platform images (amd64, arm64, s390x, ppc64le) are on Docker Hub: ```bash docker pull pambrose/prometheus-proxy:4.9.0 docker pull pambrose/prometheus-agent:4.9.0 ``` === "Helm" Install the proxy and the agent with the Helm charts in the repository's [`charts/`](https://github.com/pambrose/prometheus-proxy/tree/master/charts) directory. They run the Docker Hub images; clone the repository at the release whose images they run to use them: ```bash git clone -c advice.detachedHead=false --depth 1 --branch 4.9.0 \ https://github.com/pambrose/prometheus-proxy.git cd prometheus-proxy ``` ## 2. Start the Proxy { #start-the-proxy } The proxy runs outside the firewall, beside Prometheus. As started here, it accepts any agent and answers any scrape, with no TLS, token, or login. Try it on a network you trust. Before either port is open to a network you don't, add TLS and a token, as in [Security](https://prometheus-proxy.com/security/index.md). === "JAR" It runs in your terminal, and logs there, until you stop it with Ctrl+C: ```bash java -jar prometheus-proxy.jar ``` ??? info "Keep it running" `nohup` keeps the proxy running after you close the terminal. Send its output to a log file, and save its process ID so you can stop it later: ```bash nohup java -jar prometheus-proxy.jar > proxy.log 2>&1 & echo $! > proxy.pid ``` | To | Run | |---|---| | Follow its log | `tail -f proxy.log` | | Stop it | `kill "$(cat proxy.pid)"` | Nothing restarts it if it exits or the machine reboots. For that, use the Homebrew or Docker tab, or run it under your system's service manager, as in [Running as a service](https://prometheus-proxy.com/production/index.md#running-as-a-service). === "Homebrew" It runs in your terminal, and logs there, until you stop it with Ctrl+C: ```bash prometheus-proxy ``` ??? info "Keep it running" `brew services` runs the proxy with `$(brew --prefix)/etc/prometheus-proxy.conf`, which the formula installs as a starting point, and starts it again at login. Set the ports and agent authentication there first; to try that config in your terminal, run `prometheus-proxy --config "$(brew --prefix)/etc/prometheus-proxy.conf"`. ```bash # Start it now and at every login, then check that it's running: brew services start prometheus-proxy brew services info prometheus-proxy ``` | To | Run | |---|---| | Follow its log | `tail -f "$(brew --prefix)/var/log/prometheus-proxy.log"` | | Pick up an edited config | `brew services restart prometheus-proxy` | | Stop it, and no longer start it at login | `brew services stop prometheus-proxy` | | Remove it | `brew uninstall prometheus-proxy` | === "Docker" Docker publishes both ports on every interface, past a host firewall such as ufw. The container runs attached to your terminal, and logs there, until you stop it with Ctrl+C; `--rm` then removes it: ```bash docker run --rm -p 8080:8080 -p 50051:50051 \ pambrose/prometheus-proxy:4.9.0 ``` To keep the scrape port to Prometheus, as for production, see the Docker page's [Production Setup](https://prometheus-proxy.com/docker/index.md#production-setup). ??? info "Keep it running" `--detach` starts the container and returns, and `--restart unless-stopped` starts it again if it exits or Docker restarts, until you stop it. Docker doesn't allow `--rm` with `--restart`, so the stopped container stays until you remove it: ```bash docker run --detach --name prometheus-proxy --restart unless-stopped \ -p 8080:8080 -p 50051:50051 \ pambrose/prometheus-proxy:4.9.0 # Check that it started: docker logs prometheus-proxy ``` | To | Run | |---|---| | Follow its log | `docker logs --follow prometheus-proxy` | | Restart it | `docker restart prometheus-proxy` | | Stop it, and no longer restart it | `docker stop prometheus-proxy` | | Remove the stopped container | `docker rm prometheus-proxy` | === "Helm" Install the proxy in the cluster where Prometheus runs; Kubernetes keeps it running: ```bash helm install prometheus-proxy ./charts/prometheus-proxy \ --namespace monitoring --create-namespace # Wait until it's up: kubectl --namespace monitoring rollout status deployment/prometheus-proxy ``` Prometheus scrapes it at `prometheus-proxy.monitoring.svc:8080`, and agents in the same cluster connect to `prometheus-proxy.monitoring.svc:50051`. For agents in other clusters, add `--set agentService.enabled=true`. It exposes the gRPC port through a LoadBalancer Service, `prometheus-proxy-agents`. | To | Run | |---|---| | Follow its log | `kubectl --namespace monitoring logs --follow deployment/prometheus-proxy` | | Remove it | `helm uninstall prometheus-proxy --namespace monitoring` | Its log says when it's up: ``` { .text .pp-output .pp-output--ok title="The proxy's log" } Listening for gRPC traffic on port 50051 using plaintext Responding at http://0.0.0.0:8080 All Proxy services healthy ``` Embedding the agent in a JVM app? The proxy is all you need from this page: go back to your [JVM Embed](https://prometheus-proxy.com/embed/index.md) guide, whose agent takes the place of step 3's. ## 3. Start the Agent { #start-the-agent } The agent runs inside the firewall, beside your services. A config file says which of their metrics endpoints it serves, and at which path on the proxy. ### Create an Agent Config [HOCON](https://prometheus-proxy.com/glossary/index.md#hocon) is the format of the proxy's and the agent's config files: JSON that also allows comments, unquoted strings, and dotted keys such as `proxy.hostname`. Create a file called `./agent.conf`. Each entry in its `pathConfigs` serves one endpoint: Prometheus scrapes the entry's `path` on the proxy, and the agent fetches its `url`: === "JAR" ```hocon agent { proxy.hostname = "proxy-host.example.com" pathConfigs: [ { name: "My App metrics" path: my_app_metrics url: "http://localhost:9100/metrics" } ] } ``` Or download [`examples/agent.conf`](https://prometheus-proxy.com/examples/index.md#production-agent-agentconf), which sets the same proxy and endpoint, with the agent's production settings ready to turn on: ```bash curl -fL -o agent.conf https://raw.githubusercontent.com/pambrose/prometheus-proxy/4.9.0/examples/agent.conf ``` === "Homebrew" ```hocon agent { proxy.hostname = "proxy-host.example.com" pathConfigs: [ { name: "My App metrics" path: my_app_metrics url: "http://localhost:9100/metrics" } ] } ``` Or download [`examples/agent.conf`](https://prometheus-proxy.com/examples/index.md#production-agent-agentconf), which sets the same proxy and endpoint, with the agent's production settings ready to turn on: ```bash curl -fL -o agent.conf https://raw.githubusercontent.com/pambrose/prometheus-proxy/4.9.0/examples/agent.conf ``` === "Docker" In a container, `localhost` is the container itself. So the `url` names the machine Docker runs on, `host.docker.internal`, which the `docker run` below defines on Linux too. To try it all on one machine, use it for `proxy.hostname` as well: ```hocon agent { proxy.hostname = "proxy-host.example.com" pathConfigs: [ { name: "My App metrics" path: my_app_metrics url: "http://host.docker.internal:9100/metrics" } ] } ``` === "Helm" In a pod, `localhost` is the agent itself, so the `url` names the app's Service. The chart sets the proxy, below: ```hocon agent { pathConfigs: [ { name: "My App metrics" path: my_app_metrics url: "http://my-app.default.svc.cluster.local:9100/metrics" } ] } ``` ### Run the Agent { #start-it } === "JAR" Run it in a second terminal, where it logs until you stop it with Ctrl+C: ```bash java -jar prometheus-agent.jar --config agent.conf ``` `--proxy proxy-host.example.com` names the proxy on the command line instead, and overrides the file's `agent.proxy.hostname`. ??? info "Keep it running" `nohup` keeps the agent running after you close the terminal. Send its output to a log file, and save its process ID so you can stop it later: ```bash nohup java -jar prometheus-agent.jar --config agent.conf > agent.log 2>&1 & echo $! > agent.pid ``` | To | Run | |---|---| | Follow its log | `tail -f agent.log` | | Stop it | `kill "$(cat agent.pid)"` | To pick up an edited `./agent.conf`, stop the agent and start it again. Nothing restarts it if it exits or the machine reboots. For that, use the Homebrew or Docker tab, or run it under your system's service manager, as in [Running as a service](https://prometheus-proxy.com/production/index.md#running-as-a-service). === "Homebrew" Run it in a second terminal, where it logs until you stop it with Ctrl+C: ```bash prometheus-agent --config agent.conf ``` `--proxy proxy-host.example.com` names the proxy on the command line instead, and overrides the file's `agent.proxy.hostname`. ??? info "Keep it running" `brew services` runs the agent with `$(brew --prefix)/etc/prometheus-agent.conf` and starts it again at login. The formula installs a starting point there with no paths, so copy your `./agent.conf` over it first. The service passes no `--proxy`, so the file's `agent.proxy.hostname` decides which proxy the agent connects to: ```bash cp agent.conf "$(brew --prefix)/etc/prometheus-agent.conf" # Start it now and at every login, then check that it's running: brew services start prometheus-agent brew services info prometheus-agent ``` | To | Run | |---|---| | Follow its log | `tail -f "$(brew --prefix)/var/log/prometheus-agent.log"` | | Pick up an edited config | `brew services restart prometheus-agent` | | Stop it, and no longer start it at login | `brew services stop prometheus-agent` | | Remove it | `brew uninstall prometheus-agent` | === "Docker" Run it in a second terminal, where it logs until you stop it with Ctrl+C; `--rm` then removes the container. `--add-host` defines `host.docker.internal` on Linux; Docker Desktop has it already: ```bash docker run --rm \ --add-host=host.docker.internal:host-gateway \ --mount type=bind,source="$(pwd)"/agent.conf,target=/app/agent.conf \ --env AGENT_CONFIG=agent.conf \ pambrose/prometheus-agent:4.9.0 ``` ??? info "Keep it running" `--detach` starts the container and returns, and `--restart unless-stopped` starts it again if it exits or Docker restarts, until you stop it. Docker doesn't allow `--rm` with `--restart`, so the stopped container stays until you remove it: ```bash docker run --detach --name prometheus-agent --restart unless-stopped \ --add-host=host.docker.internal:host-gateway \ --mount type=bind,source="$(pwd)"/agent.conf,target=/app/agent.conf \ --env AGENT_CONFIG=agent.conf \ pambrose/prometheus-agent:4.9.0 # Check that it connected: docker logs prometheus-agent ``` | To | Run | |---|---| | Follow its log | `docker logs --follow prometheus-agent` | | Pick up an edited `./agent.conf` | `docker restart prometheus-agent` | | Stop it, and no longer restart it | `docker stop prometheus-agent` | | Remove the stopped container | `docker rm prometheus-agent` | === "Helm" Install the agent with the `./agent.conf` above; Kubernetes keeps it running. The chart's `proxy.hostname` is the proxy's gRPC address, as `host:port`. In the proxy's cluster, that's the proxy's Service: ```bash helm install prometheus-agent ./charts/prometheus-agent \ --set proxy.hostname=prometheus-proxy.monitoring.svc:50051 \ --set-file config=agent.conf # Wait until it's up: kubectl rollout status deployment/prometheus-agent ``` From another cluster, set `proxy.hostname` to the external address of the proxy's LoadBalancer Service, with `:50051`. The proxy's chart creates that Service, `prometheus-proxy-agents`, when installed with `--set agentService.enabled=true`. In the proxy's cluster, its `EXTERNAL-IP` column shows the address: ```bash kubectl --namespace monitoring get service prometheus-proxy-agents ``` | To | Run | |---|---| | Follow its log | `kubectl logs --follow deployment/prometheus-agent` | | Remove it | `helm uninstall prometheus-agent` | See [Kubernetes](https://prometheus-proxy.com/kubernetes/index.md#installing-with-helm) for TLS, agent tokens, and discovery. Its log says when it has connected and registered each path: ``` { .text .pp-output .pp-output--ok title="The agent's log" } Connected to proxy at proxy-host.example.com:50051 using plaintext Registered http://localhost:9100/metrics as /my_app_metrics with labels {} (static) ``` If it logs `Cannot connect to proxy at …` instead, it can't reach the proxy's port 50051. Check the proxy's address the agent was given, and that the agent's host may connect out to that port; the agent keeps trying every 3 seconds. See [Agent Can't Connect to the Proxy](https://prometheus-proxy.com/troubleshooting/index.md#agent-cant-connect-to-the-proxy). ## 4. Configure Prometheus { #configure-prometheus } Add a job that scrapes the agent's path on the proxy. The `metrics_path` is the `path` in the agent's `pathConfigs`: ```yaml scrape_configs: - job_name: 'my-app' metrics_path: '/my_app_metrics' static_configs: - targets: ['proxy-host.example.com:8080'] ``` On Kubernetes, the target is the proxy's Service, `prometheus-proxy.monitoring.svc:8080`; with the Prometheus Operator, add a `ServiceMonitor` instead, as in [Prometheus Integration](https://prometheus-proxy.com/kubernetes/index.md#prometheus-integration). Then have Prometheus read the job: send it a `SIGHUP`, or `POST` to its `/-/reload` endpoint when it runs with `--web.enable-lifecycle`. ## 5. Verify { #verify } Scrape the path through the proxy, as Prometheus will: === "JAR" ```bash curl -i http://proxy-host.example.com:8080/my_app_metrics ``` === "Homebrew" ```bash curl -i http://proxy-host.example.com:8080/my_app_metrics ``` === "Docker" ```bash curl -i http://proxy-host.example.com:8080/my_app_metrics ``` === "Helm" The proxy's scrape port is inside the cluster. From your workstation, forward it, scrape through it, and stop the forward: ```bash kubectl --namespace monitoring port-forward service/prometheus-proxy 8080:8080 & sleep 2 # give the forward a moment to start curl -i http://localhost:8080/my_app_metrics kill "$!" # stop the forward ``` HTTP/1.1 200 OK, followed by the metrics the app serves at `:9100/metrics`, means every hop works. The proxy answers scrapes, the agent is connected and has registered the path, and the agent can reach the target. !!! success "You're done when Prometheus shows `my-app` up" After Prometheus's next scrape, open its target page (Status → Target health). It shows `my-app` as up: Prometheus is scraping a service behind the firewall, by pull, through the proxy. If you get anything else, it says which hop failed: - **`curl` can't connect**: nothing answers on the proxy's port 8080. Check that the proxy is running, and that the port is open to you. - 404 Not Found: no agent has registered the path, or the target itself answered 404. Check the agent's log for the `Registered` line ([step 3](#start-it)), and that the path matches the agent's `path`. If both are right, check the `url` with `curl` from the agent's host. See [404 Not Found](https://prometheus-proxy.com/troubleshooting/index.md#404-not-found). - 503 Service Unavailable: the agent has the path, but it couldn't reach the target, or it was disconnected. Check the `url` with `curl` from the agent's host. See [503 Service Unavailable](https://prometheus-proxy.com/troubleshooting/index.md#503-service-unavailable). - 408 Request Timeout: the target didn't answer within the agent's scrape timeout: `agent.scrapeTimeoutSecs`, 15 seconds by default, or Prometheus's `scrape_timeout` if that's shorter. Time the `url` with `curl` from the agent's host. If the target is slow but working, raise the timeouts, as in [408 Request Timeout and Other Timeouts](https://prometheus-proxy.com/troubleshooting/index.md#scrape-hangs-then-times-out). [Troubleshooting](https://prometheus-proxy.com/troubleshooting/index.md#prometheus-scrape-returns-an-error) covers every status. ## 6. See It in the Dashboard { #dashboard } This step is optional: you're done once Prometheus shows `my-app` up. The proxy's [dashboard](https://prometheus-proxy.com/web-dashboard/index.md) puts every path on one page, beside the agent serving it, its target URL, and its recent scrapes. When a scrape fails, it shows why. The dashboard is off by default, so this step restarts the proxy with it on. Nothing else changes, and nothing else needs restarting: - **The agent reconnects by itself.** While the proxy is down, it logs `Cannot connect to proxy at …` and tries again every 3 seconds. Once the proxy is back, it connects and registers its path again. - **Prometheus may miss a scrape** during the restart. Then it scrapes as before, with the same job. The dashboard has no TLS, and no [login](https://prometheus-proxy.com/web-dashboard/index.md#login) until you set a password. So the commands below keep it local: on the proxy's host, or, with Helm, behind a port-forward. === "JAR" Stop the proxy with Ctrl+C, and start it again with the dashboard on, listening on the proxy's host only: ```bash java -jar prometheus-proxy.jar --dashboard --dashboard_host 127.0.0.1 ``` If you started it with `nohup`, stop it with `kill "$(cat proxy.pid)"` instead, and start it again the same way, with the two flags. === "Homebrew" Stop the proxy with Ctrl+C, and start it again with the dashboard on, listening on the proxy's host only: ```bash prometheus-proxy --dashboard --dashboard_host 127.0.0.1 ``` If `brew services` runs it, add `dashboard.enabled = true` and `dashboard.host = "127.0.0.1"` to the `proxy` block of `$(brew --prefix)/etc/prometheus-proxy.conf` instead, and run `brew services restart prometheus-proxy`. === "Docker" Stop the container with Ctrl+C, and run it again with the dashboard on, its port published on your host's `127.0.0.1` only: ```bash docker run --rm -p 8080:8080 -p 50051:50051 \ -p 127.0.0.1:8094:8094 --env DASHBOARD_ENABLED=true \ pambrose/prometheus-proxy:4.9.0 ``` The proxy warns that the dashboard has no login and listens on all interfaces. Inside the container it has to, for Docker to reach it; the `127.0.0.1:` before the published port is what keeps it on your host. If the container runs detached, remove it with `docker rm --force prometheus-proxy`, and run it again with the same two additions. === "Helm" Upgrade the release with the dashboard on. The chart has the dashboard listen on the pod's loopback (`dashboard.host`, `127.0.0.1`) and leaves it off the Service, so only `kubectl port-forward` reaches it: ```bash helm upgrade prometheus-proxy ./charts/prometheus-proxy \ --namespace monitoring --reuse-values --set dashboard.enabled=true kubectl --namespace monitoring rollout status deployment/prometheus-proxy # Forward the dashboard's port until you stop it with Ctrl+C: kubectl --namespace monitoring port-forward deployment/prometheus-proxy 8094:8094 ``` Open `http://localhost:8094/dashboard/paths`. If your browser runs on another host than the proxy, outside Kubernetes, first forward the port over SSH. Then open the same address: ```bash ssh -N -L 8094:127.0.0.1:8094 proxy-host.example.com ``` The **Paths** view lists `/my_app_metrics`, beside the agent serving it and its target URL, the `url` in `./agent.conf`. The restarted proxy has no scrapes of the path yet, so run [step 5](#verify)'s `curl` again, or wait for Prometheus's next scrape. The row shows the scrape as it lands, with no reload: its time, its status, 200, and a green dot in **History**, which keeps the path's last 20 scrapes. A scrape that fails shows its status in red. **Problems only**, above the table, keeps just the paths whose last scrape failed or whose agent has gone.
![The Basics Demo's Paths view: nine paths, each beside its agent and target URL, every last scrape a 200, and each path's history a row of green dots](https://prometheus-proxy.com/images/demo/layout-paths-top.webp)
The Basics Demo's Paths view, with nine paths; yours lists one
The [Proxy Dashboard](https://prometheus-proxy.com/web-dashboard/index.md) page covers the rest: the **Agents**, **Activity**, and **Settings** views, Scrape now, and links from each path into other tools, such as Grafana. ## Next Steps
- [Try a demo](https://prometheus-proxy.com/demos/index.md) One `make up` runs the proxy, its agents, and Prometheus on your laptop, in Docker, with a guided tour. Start with the Basics Demo; the Demos page lists six more: a simulated WAN, nginx, Kubernetes, and three apps that embed the agent. - [Share the dashboard](https://prometheus-proxy.com/dashboard-exposure/index.md) Before your team opens it: a login, a reverse proxy in front of it, the ports to firewall, and running it on an HA pair. - [Configure the agent](https://prometheus-proxy.com/configuration/agent/index.md) Several endpoints from one agent, labels, filters, discovery, failover, a config served from a URL, and every other setting. - [Secure it](https://prometheus-proxy.com/security/index.md) TLS between the proxy and its agents, agent tokens, an identity for each team's agents, and forwarding a target's credentials. - [Run it in production](https://prometheus-proxy.com/production/index.md) A checklist for running it for real, with the Docker and Kubernetes pages for each. - [Embed the agent](https://prometheus-proxy.com/embedded-agent/index.md) Run the agent inside a JVM app, by hand or through the Ktor plugin or the Spring Boot starter.
--- Source: https://prometheus-proxy.com/architecture/ # Architecture Prometheus Proxy is two services, a proxy outside the firewall and an agent inside it, joined by a gRPC connection the agent opens. This page covers what each one does, how a scrape travels between them, and what happens to a payload on the way: filtering, compression, and chunking. Read it before you deploy or tune the two, to know which side each setting acts on, and which side to look at when a scrape fails. ## Components ### Proxy The proxy runs outside the firewall, beside the Prometheus server. It serves the paths Prometheus scrapes over HTTP and accepts the agents' persistent gRPC connections, on ports 8080 and 50051 by default. It can also serve a [service discovery](https://prometheus-proxy.com/service-discovery/index.md) endpoint, so Prometheus finds the paths on its own, and admin and metrics endpoints, for health checks and its operational metrics. ### Agent The agent runs inside the firewall, beside the services it monitors. It opens an *outbound* gRPC connection to the proxy and keeps it open, registers its configured paths with the proxy, and scrapes each path's metrics endpoint when the proxy asks, on Prometheus's behalf. While the connection is quiet, it sends heartbeats to keep it alive. ## Request Flow ``` mermaid %%{init: {'sequence': {'actorMargin': 16, 'width': 130, 'wrap': true}}}%% sequenceDiagram accTitle: Request flow accDescr { Prometheus and the proxy are outside the firewall; the agent and the app it scrapes are inside. The agent connects out to the proxy's gRPC port when it starts, registers itself, and registers the path /app_metrics. When Prometheus scrapes /app_metrics on the proxy's port 8080, the proxy looks up the agent for the path and sends it a scrape request over the stream. The agent fetches /metrics from the app on port 9100 and sends the response back over the stream, and the proxy returns it to Prometheus. } %% The firewall runs between the two boxes, as between the flowcharts' zones: every arrow across it travels on %% the connection the agent opened from inside. The inside box's color, orange, marks it as the firewall's, which %% javascripts/diagrams.js outlines in the accent, as the flowcharts' firewall class does; it fills no box. box Outside Firewall participant P as Prometheus participant Proxy as Proxy :8080 participant gRPC as Proxy gRPC :50051 end box orange Inside Firewall participant Agent as Agent participant App as App :9100/metrics end Note over Agent, gRPC: Agent connects on startup (outbound) Agent->>gRPC: connectAgent() Agent->>gRPC: registerAgent() Agent->>gRPC: registerPath
("/app_metrics") Note over P, Proxy: Prometheus scrapes as normal P->>Proxy: GET /app_metrics Proxy->>gRPC: Lookup agent for path gRPC->>Agent: ScrapeRequest (via stream) Agent->>App: GET /metrics App-->>Agent: Metrics response Agent-->>gRPC: ScrapeResponse (via stream) gRPC-->>Proxy: Route response Proxy-->>P: Return metrics ``` ## gRPC Protocol The proxy and the agent talk over gRPC, in both directions, with the service `proxy_service.proto` defines. Its main calls: | RPC | Type | Description | |:-------------------------------|:-----------------|:-------------------------------------------------| | `connectAgent` | Unary | Agent announces its presence | | `registerAgent` | Unary | Register agent identity and metadata | | `registerPath` | Unary | Register a scrape path with optional labels | | `unregisterPath` | Unary | Remove a previously registered path | | `readRequestsFromProxy` | Server-streaming | Proxy sends scrape requests to agent | | `writeResponsesToProxy` | Client-streaming | Agent sends scrape responses back | | `writeChunkedResponsesToProxy` | Client-streaming | Agent sends chunked responses for large payloads | | `sendHeartBeat` | Unary | Keep-alive during periods of inactivity | | `readPathNoticesFromProxy` | Server-streaming | Proxy tells agent another agent took its path, or that the path is free again | ## Chunking The agent splits a large response into chunks, to stay within gRPC's message size limits. - It chunks a response once its gzipped size reaches `chunkContentSizeKbs` (32 KB by default). A response too small to gzip is never chunked. - It sends a chunked response as `ChunkedScrapeResponse` messages: - A **header** with the response's metadata: its status, content type, and URL. - One or more **chunks** of its bytes, each with a CRC32 checksum. - A **summary** with the total byte count and a final checksum. - The proxy puts the chunks back together and checks them against the checksums before it answers Prometheus. Configure the chunk threshold: ```hocon agent.chunkContentSizeKbs = 64 // Larger chunks for big payloads ``` ## Compression The agent gzips a response larger than `minGzipSizeBytes` (512 bytes by default) before it sends it over gRPC, which saves bandwidth between the agent and the proxy. ```hocon agent.minGzipSizeBytes = 256 // Compress more aggressively ``` ## Metric Filtering Chunking and compression both manage the *size* of a payload; neither reduces the content itself. An optional per-path filter drops whole metric families at the agent, so unwanted series never cross the network boundary at all, which cuts bandwidth, and Prometheus's cardinality, at the source. Filtering runs between the scrape and the gzip decision, so the three mechanisms compose in pipeline order: ``` scrape target -> filter -> gzip (minGzipSizeBytes) -> chunk (chunkContentSizeKbs) -> gRPC ``` Because the filter runs first, gzip and chunking both see the already-reduced payload. The `maxContentLengthMBytes` guard is the deliberate exception: it applies to the raw response, so filtering can never be a way around that limit. Filtering is off by default and configured per path. See [Metric Filtering](https://prometheus-proxy.com/configuration/agent/index.md#metric-filtering) for the rules and configuration. ## Heartbeat While its gRPC connection is quiet, the agent sends heartbeats over it, so load balancers and firewalls don't close it as idle. A reverse proxy such as nginx can still close a quiet stream on the connection, so each stream also sends a keepalive after `proxy.internal.streamKeepAliveSecs` (default: 30s) without a message, once the agent and the proxy have both said at registration that they take them. ```hocon agent.internal { heartbeatEnabled = true heartbeatCheckPauseMillis = 500 heartbeatMaxInactivitySecs = 5 // Send heartbeat after 5s of inactivity } ``` ## Connection Lifecycle 1. **Startup**: the agent reads its configuration and starts its services. 2. **Connection**: it opens an outbound gRPC connection to the proxy. 3. **Registration**: it registers itself and its configured paths. A path refused because a live agent holds it is retried while the agent stays connected, first after `agent.internal.rejectedPathRetrySecs` for a static path, or `agent.discovery.reconcileIntervalSecs` for a discovered one, and then on a backoff that doubles up to `agent.internal.rejectedPathRetryMaxSecs`. 4. **Operation**: it serves the proxy's scrape requests and sends heartbeats. 5. **Reconnection**: when its connection drops, it reconnects by itself, trying at most once every `agent.internal.reconnectPauseSecs` (3 seconds by default). 6. **Shutdown**: it closes its connections and releases what it holds. ## Stale Agent Cleanup The proxy runs a background service that evicts agents that have been inactive for too long: ```hocon proxy.internal { staleAgentCheckEnabled = true maxAgentInactivitySecs = 60 // Evict after 60s of inactivity staleAgentCheckPauseSecs = 10 // Check every 10s } ``` ## Consolidated Mode By default, each path is owned by a single agent. In **consolidated mode**, several agents serve one path, and the proxy merges their answers to each scrape. [Consolidated Mode](https://prometheus-proxy.com/advanced/index.md#consolidated-mode) explains it. --- Source: https://prometheus-proxy.com/coding-agents/ # Using a Coding Agent A coding agent, such as Claude Code or Codex, that builds an app with Prometheus Proxy can read the project's instructions as it works: a skill to install, the docs as Markdown, and a block of rules to keep in the app's repository. Then check what it wrote as you would check your own. ## Install the Skill The skill helps a coding agent: - choose between a standalone agent and one embedded in the app; - embed the agent in a JVM app, with the Ktor plugin, or with the Spring Boot starter; - configure the proxy and standalone agents, with tokens and TLS; - write Prometheus's scrape config for the proxy's paths; - find why a scrape through the proxy fails. Its examples are the docs', which the project's build compiles and tests. In Claude Code 2.1.275 or later: ```text /plugin install prometheus-proxy --marketplace pambrose/prometheus-proxy ``` In earlier versions, add the marketplace, then install the plugin: ```text /plugin marketplace add pambrose/prometheus-proxy /plugin install prometheus-proxy@prometheus-proxy ``` Or from a shell: ```bash claude plugin marketplace add pambrose/prometheus-proxy claude plugin install prometheus-proxy@prometheus-proxy ``` ### Other Coding Agents The skill is in the [Agent Skills](https://agentskills.io/) format, so another coding agent that reads the format can use its directory, [`plugins/prometheus-proxy/skills/prometheus-proxy`](https://github.com/pambrose/prometheus-proxy/tree/master/plugins/prometheus-proxy/skills/prometheus-proxy), as it is. Copy it to where the coding agent reads skills, such as `.agents/skills/` in the app's repository for Codex, or `.claude/skills/` for Claude Code. From the app's repository: ```bash tmp=$(mktemp -d) git clone --depth 1 https://github.com/pambrose/prometheus-proxy.git "$tmp" mkdir -p .agents/skills cp -R "$tmp/plugins/prometheus-proxy/skills/prometheus-proxy" .agents/skills/ ``` ## The Docs as Markdown Every page of these docs is also served as Markdown, with its code examples in place, for a coding agent to read: add `index.md` to a page's URL, as in . - [`llms.txt`](https://prometheus-proxy.com/llms.txt) tells a coding agent what the project is, which way to run the agent, and the rules for its code and config, then links to each page's Markdown. - [`llms-full.txt`](https://prometheus-proxy.com/llms-full.txt) holds every page but the demos' in one file. Point a coding agent without the skill at `llms.txt` before it starts. The rules below do that for every session. ## Rules for Your App's AGENTS.md A coding agent reads the instructions in a repository's `AGENTS.md` at the start of every session. Paste this block into your app's, so the coding agent reads the docs before it writes code or config for Prometheus Proxy, and avoids the mistakes that make a setting do nothing or a scrape fail: ```markdown ## Prometheus Proxy Prometheus scrapes this app's metrics through Prometheus Proxy: Prometheus scrapes a proxy outside the firewall, which passes each scrape to an agent inside it, over a gRPC connection the agent opened to the proxy. - **Read the docs first.** Before writing code or config for Prometheus Proxy, use the prometheus-proxy skill if it's installed, or else read https://prometheus-proxy.com/llms.txt, then the pages it links to for the task. Write for the release this app's build names. The docs describe the latest release, and when the build names an older one, the upgrading pages say what each release changed: for a standalone proxy and agent, https://prometheus-proxy.com/upgrading/index.md, and for an embedded agent, https://prometheus-proxy.com/embedded-upgrading/index.md. - **Use only settings that exist.** A config key the agent or the proxy doesn't know has no effect. Take keys from the docs' configuration pages, and in an embedded agent prefer the builder's typed methods to `setting(key, value)`. After changing a config, check the startup log for this WARN, which names the key, and the nearest setting when one is near: `isn't a setting, so it has no effect`. Spring Boot ignores a `prometheus-proxy.agent` property it doesn't know, so check those against https://prometheus-proxy.com/spring-boot-starter/#properties. - **Prometheus scrapes the proxy, not the app.** Its target is the proxy's scrape port, 8080 by default, and its `metrics_path` is the path the agent registered, with one leading slash. - **Secrets come from the environment,** never a committed file. An embedded agent's `fromEnvironment()` reads `PROMETHEUS_PROXY`, `PROMETHEUS_AGENT_TOKEN`, and `PROMETHEUS_PROXY_CERT`, and a standalone agent reads its token from `AGENT_TOKEN`. - **Start and stop an embedded agent with the app.** `startIfConfigured()` returns null when no proxy is set, so the app runs without it. Close the `EmbeddedAgentInfo` it returns when the app stops. The Ktor plugin and the Spring Boot starter do both. ``` ## Check What It Wrote Three checks show that the code and config work: 1. **Every setting exists.** At startup, the agent and the proxy each log a WARN for every key in their config section that isn't a setting, naming the nearest setting when one is near. A coding agent that names a setting from memory can name one that never existed: ``` { .text .pp-output title="The agent's log" } agent.scrapeTimeoutSec isn't a setting, so it has no effect; did you mean agent.scrapeTimeoutSecs? ``` Spring Boot ignores a `prometheus-proxy.agent` property it doesn't know, so check a Spring Boot app's against the starter's [Properties](https://prometheus-proxy.com/spring-boot-starter/index.md#properties). 2. **The agent registered its paths.** Its log says it connected to the proxy, then registered each path, with the target it scrapes, or `in-process` for a registry it reads: ``` { .text .pp-output .pp-output--ok title="The agent's log" } Connected to proxy at localhost:50051 using plaintext Registered in-process as /my_app_metrics with labels {} (static) ``` 3. **The path scrapes through the proxy,** as Prometheus will scrape it: ```bash curl -i http://localhost:8080/my_app_metrics ``` HTTP/1.1 200 OK, followed by the metrics, means every hop works. When one of them fails, [Troubleshooting](https://prometheus-proxy.com/troubleshooting/index.md) goes through the causes, and [Debugging an Embedded Agent](https://prometheus-proxy.com/embedded-debugging/index.md) shows where an embedded agent logs and what else to look at. --- Source: https://prometheus-proxy.com/configuration/ # Configure The proxy and the agent each take their settings from command-line options, environment variables, `-D` properties, a config file, and built-in defaults. Below the list of pages, this page covers which setting wins and how a config file is written: read it before you write a first config, or when a value you set doesn't take.
- [Agent Configuration](https://prometheus-proxy.com/configuration/agent/index.md) Each setting of the agent: the paths it serves and their targets, its connection to the proxy and failover, dynamic target discovery, metric filters, scraping, and its dashboard and metrics. - [Proxy Configuration](https://prometheus-proxy.com/configuration/proxy/index.md) Each setting of the proxy: its scrape and agent ports, agent tokens and per-agent identities, service discovery, its dashboard and screens page, its metrics, and the limits on what agents may register. - [Security](https://prometheus-proxy.com/security/index.md) Who may connect as an agent, which paths each may register, who can reach the scrape port and the dashboard, and how credentials are protected, with TLS between the proxy and its agents in TLS Setup. - [Prometheus Service Discovery](https://prometheus-proxy.com/service-discovery/index.md) The proxy's endpoint for Prometheus's HTTP service discovery, from which Prometheus finds each path the agents register, with no change to its config. - [Example Configs](https://prometheus-proxy.com/examples/index.md) Ready-to-run config files from the repository: self-monitoring, several endpoints, metric filters, a discovery file, federation, and TLS.
## Which Setting Wins The proxy and the agent both use the [Typesafe Config](https://github.com/lightbend/config) library, and take a setting from the first of these that sets it: ```text Configuration precedence (highest to lowest): 1. CLI options: --port 9090 2. Environment vars: PROXY_PORT=9090 3. Dynamic properties: -Dproxy.http.port=9090 4. Config file: proxy.http.port = 9090 5. Default values: 8080 ``` ## Configuration Formats Typesafe Config supports three formats: | Format | Extension | Description | |:---------------|:--------------|:-------------------------------------------| | **HOCON** | `.conf` | Human-friendly JSON superset (recommended) | | **JSON** | `.json` | Standard JSON format | | **Properties** | `.properties` | Java properties format | ## Loading Configuration ### From a Local File ```bash java -jar prometheus-agent.jar --config /etc/prometheus-proxy/agent.conf java -jar prometheus-proxy.jar --config /etc/prometheus-proxy/proxy.conf ``` ### From a URL ```bash # Load configuration from a URL: java -jar prometheus-agent.jar \ --config https://raw.githubusercontent.com/pambrose/prometheus-proxy/4.9.0/examples/simple.conf # Or from a local file: java -jar prometheus-agent.jar --config /etc/prometheus-proxy/agent.conf ``` ### Dynamic Properties Set any scalar configuration value with a `-D` flag. It overrides the config file, but a CLI option or environment variable for the same setting overrides it: ```bash java -jar prometheus-proxy.jar -Dproxy.http.port=9090 -Dproxy.admin.enabled=true java -jar prometheus-agent.jar -Dagent.proxy.hostname=myproxy.com --config agent.conf ``` ## Environment Variables Each everyday setting has an environment variable, which a container or a systemd unit can set without a config file. A few of each side's: ```text Common environment variables: Proxy: PROXY_CONFIG - Config file path or URL PROXY_PORT - HTTP listen port (default: 8080) AGENT_PORT - gRPC listen port (default: 50051) ADMIN_ENABLED - Enable admin endpoints METRICS_ENABLED - Enable metrics collection SD_ENABLED - Enable service discovery Agent: AGENT_CONFIG - Config file path or URL (required) PROXY_HOSTNAME - Proxy hostname AGENT_NAME - Agent name for metrics ADMIN_ENABLED - Enable admin endpoints METRICS_ENABLED - Enable metrics collection MAX_CONCURRENT_CLIENTS - Parallel scrape limit ``` See the [CLI Reference](https://prometheus-proxy.com/cli-reference/index.md) for the complete list. ## HOCON Basics HOCON (Human-Optimized Config Object Notation) is a superset of JSON, with comments, unquoted strings, and substitutions: ```hocon // Comments start with // or # agent { // Nested keys with dot notation proxy.hostname = "proxy-host.example.com" proxy.port = 50051 // Arrays use brackets pathConfigs: [ { name: "My App" path: my_app_metrics url: "http://localhost:9100/metrics" } ] // Reference environment variables name = ${?AGENT_NAME} } ``` What the example uses, and two features it doesn't: - A comment starts with `#` or `//`. - A simple value needs no quotes. - `${?VAR_NAME}` substitutes an environment variable, and leaves the setting alone when the variable isn't set. - A dotted key, such as `agent.proxy.hostname`, sets a nested setting. - `include "other.conf"` reads another file into this one. An object set twice is merged, and a value set twice takes the later one. ## Configuration Reference The reference file, [`config/config.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/config/config.conf), declares every setting, with its default. The [CLI Reference](https://prometheus-proxy.com/cli-reference/index.md) gives the command-line option and environment variable of each setting that has them. A key the reference file doesn't declare, misspelled or made up, has no effect. The proxy and the agent each log a WARN at startup for every such key in their own section, `proxy` or `agent`, naming the nearest setting when one is near, and leave a file's other sections alone, so one file can hold both: ```text agent.scrapeTimeoutSec isn't a setting, so it has no effect; did you mean agent.scrapeTimeoutSecs? ``` --- Source: https://prometheus-proxy.com/configuration/agent/ # Agent Configuration The agent runs inside the firewall and scrapes local metrics endpoints on behalf of the proxy. The settings below are keys in the agent's config file. Each section's table gives a key over its command-line option and environment variable, where it has them, and links the key to its row in the [CLI Reference](https://prometheus-proxy.com/cli-reference/index.md#agent-options). A key with neither is set in the config file, or with `-D`. | Section | Covers | |:-----------------------------------------------------------------|:----------------------------------------------------------| | [Path Configs](#path-configs) | `agent.pathConfigs`: each path and the URL it scrapes | | [Dynamic Target Discovery](#dynamic-target-discovery) | `agent.discovery`: paths from a watched file, no restart | | [Proxy Connection](#proxy-connection) | `agent.proxy`: the proxy, or proxies to fail over between | | [Agent Authentication](#agent-authentication) | `agent.agentToken`: the token the proxy requires | | [gRPC Settings](#grpc-settings) | `agent.grpc`: keepalive PINGs and call deadlines | | [Transport Filter](#transport-filter) | `agent.transportFilterDisabled`, behind a reverse proxy | | [HTTP Client Settings](#http-client-settings) | `agent.http`: how the agent fetches its targets | | [Scraping HTTPS Endpoints](#scraping-https-endpoints) | A trust store for targets a private CA signed | | [Scrape Settings](#scrape-settings) | Timeout, retries, chunking, and gzip | | [Metric Filtering](#metric-filtering) | `agent.filters`: metric families dropped at the agent | | [Consolidated Mode](#consolidated-mode) | `agent.consolidated`: several agents serving one path | | [Agent Naming](#agent-naming) | `agent.name`, as logs and metrics show the agent | | [Admin Endpoints](#admin-endpoints) | `agent.admin`: ping, health check, and debug endpoints | | [Dashboard](#dashboard) | `agent.dashboard`: its direct and relayed dashboards | | [Metrics](#metrics) | `agent.metrics`: the agent's own metrics | | [Internal Settings](#internal-settings) | `agent.internal`: reconnects, retries, and heartbeats | | [Log Level](#log-level) | `agent.logLevel` | | [Full Example](#full-example), [Full Reference](#full-reference) | A starting point, and every setting with its default | ## Path Configs The `pathConfigs` array defines which metrics endpoints the agent exposes through the proxy. Two entries for the same path, with or without a leading `/`, fail the agent's startup, since the second would replace the first's URL. [Path rules](#path-rules) below covers what else a path may and may not be. ### Basic Configuration ```hocon agent { proxy.hostname = "proxy-host.example.com" pathConfigs: [ { name: "My App metrics" path: my_app_metrics url: "http://localhost:9100/metrics" } ] } ``` ### Multiple Endpoints Each endpoint gets a separate path on the proxy: ```hocon agent { pathConfigs: [ { name: "App1 metrics" path: app1_metrics url: "http://app1.local:9100/metrics" }, { name: "App2 metrics" path: app2_metrics url: "http://app2.local:9100/metrics" }, { name: "App3 metrics" path: app3_metrics url: "http://app3.local:9100/metrics" } ] } ``` Prometheus scrapes each path as a separate job: ```yaml scrape_configs: - job_name: 'app1' metrics_path: '/app1_metrics' static_configs: - targets: ['proxy-host.example.com:8080'] - job_name: 'app2' metrics_path: '/app2_metrics' static_configs: - targets: ['proxy-host.example.com:8080'] - job_name: 'app3' metrics_path: '/app3_metrics' static_configs: - targets: ['proxy-host.example.com:8080'] ``` ### With Labels Labels are included in service discovery responses and can be used for filtering: ```hocon agent { pathConfigs: [ { name: "Production API" path: prod_api_metrics labels: "{\"env\": \"production\", \"team\": \"backend\"}" url: "http://api.internal:9100/metrics" }, { name: "Staging API" path: staging_api_metrics labels: "{\"env\": \"staging\", \"team\": \"backend\"}" url: "http://api.staging:9100/metrics" } ] } ``` Each path config entry has these fields: | Field | Required | Description | |:---------|:---------|:--------------------------------------------------------------| | `name` | Yes | Human-readable endpoint name (for logs and debugging) | | `path` | Yes | Single URL segment on the proxy that Prometheus scrapes (no embedded `/`, not blank; no whitespace, control characters, `?`, or `#`) | | `url` | Yes | Actual metrics endpoint the agent fetches from | | `labels` | No | JSON string of labels for service discovery (default: `"{}"`); keys starting with `__` are dropped | ### Path Rules A path is one segment of plain characters: - **One URL segment.** A `path` must not contain an embedded `/`, nor a second leading one, as `//app_metrics` has. The proxy serves each registered path at `/` (a one-segment route), so a multi-segment value like `app/metrics` could never be scraped: the agent refuses a `pathConfigs` entry with one at startup, naming it, and skips a discovery entry with one, and the proxy refuses such a path at registration. Use `app_metrics` instead. - **No whitespace, control character, `?`, or `#`.** No scrape's request path can carry one, so Prometheus could never reach such a path. The agent refuses a `pathConfigs` entry with one at startup, naming it, and the proxy refuses such a path at registration. Every other character is allowed, including `.`, `-`, `~`, and `:`. - **Not a path the proxy answers itself.** The proxy refuses `favicon.ico`, and `proxy.service.discovery.path` or `proxy.internal.blitz.path` while that feature is on. - **Not blank.** An entry whose `path` is blank or just `/`, or whose `url` is blank, is skipped at startup, with a warning naming it, and the agent's other paths still register: the proxy answers a blank path with a 404, so such an entry could only ever be a dead registration. !!! warning "A client that percent-encodes a path gets a 404" The proxy matches a scrape's path as the client sends it, without decoding percent-escapes, so keep a `path` to characters a client sends as they are. A client that percent-encodes one, such as `%5F` for `_`, asks for a different path and gets a 404, and Prometheus encodes some characters itself, such as a non-ASCII letter. A `path` of ASCII letters, digits, `_`, `.`, `-`, and `~` is never encoded by anyone. ## Dynamic Target Discovery Dynamic target discovery is the agent's side of discovery: the *agent* picks up changes to the targets it scrapes, behind the firewall. The proxy's side is [Prometheus Service Discovery](https://prometheus-proxy.com/service-discovery/index.md), an endpoint where *Prometheus* finds the paths the agents register. By default `pathConfigs` is read once at startup, so adding or removing a target means editing the config and restarting the agent. Enable dynamic discovery to have the agent reconcile its registered paths against a **watched file** at runtime, with no restart, while paths that didn't change keep scraping: ```hocon agent { discovery { enabled = true file.path = "/etc/prometheus-proxy/targets.conf" // A list of paths reconcileIntervalSecs = 30 // Poll, and resync } } ``` The discovery file holds a `paths` list of the same `{ name, path, url, labels }` entries as `pathConfigs`: ```hocon paths = [ { name = "app1", path = "app1_metrics", url = "http://app1:9090/metrics" } { name = "app2", path = "app2_metrics", url = "http://app2:9090/metrics" } ] ``` Every interval the agent registers newly-listed paths, unregisters removed ones, and re-registers a path whose URL or labels changed. Because the file is a plain list, it can be **generated** rather than hand-maintained: by a Kubernetes `ConfigMap` mounted into the agent pod (see [the Kubernetes walkthrough](https://prometheus-proxy.com/kubernetes/index.md#updating-targets-without-restarting-the-agent)), an Ansible template, or a cron job querying a service registry. Automation then needs permission only to write a file, never to restart the agent, and the churning target list stays separate from the stable config holding ports, TLS, and the proxy address. A fully annotated version of this file ships as [`examples/discovery-targets.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/examples/discovery-targets.conf), shown whole on the [Example Configs](https://prometheus-proxy.com/examples/index.md) page. Its comments cover which fields are required and which have defaults, the single-segment `path` rule, HOCON substitutions, and how an empty file differs from a deleted one. | Situation | Behavior | |:-------------------------------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Path in both `pathConfigs` and the file | Static wins; the discovered entry is skipped (logged) | | File missing / unreadable / malformed | Keeps the last-known-good set (a read failure drops nothing), and registers it again after a reconnect | | Valid but empty file | Removes all discovered paths | | Entry with a blank `path` (or just `/`) or `url` | Skipped when the file is read, reported once until the set of skipped entries changes; the file's other entries still apply | | Entry whose `path` has more than one segment | Skipped the same way, whether `app/metrics` or `//app_metrics`, whose first segment is empty | | Seeing what discovery did | The agent's `/debug` page lists the discovered paths it registered and the entries it skipped | | `pathConfigs` empty | Every path comes from the file | | Proxy rejects a discovered path | Logged once. A rejection that can clear is retried with a backoff: on the next poll, then after one `reconcileIntervalSecs`, then after waits that double up to `agent.internal.rejectedPathRetryMaxSecs` (5 min). Any other rejection is tried again only when the entry changes or the agent reconnects | The agent's `agent_discovery_skipped_entries` gauge counts the entries the last read skipped ([Agent Metrics](https://prometheus-proxy.com/monitoring/index.md#agent-metrics)), and the `AgentDiscoverySkippedEntries` alert in the project's [alerting rules](https://prometheus-proxy.com/grafana/index.md#alerting-rules) warns once one has stayed 5 minutes. ??? info "Polling, not file-watching" Discovery polls the file on the interval rather than relying on OS file-change events, which are unreliable under Kubernetes ConfigMap updates (symlink swaps) and some bind mounts. The interval doubles as a full-resync safety net. !!! note "Config-file only" `discovery.file.path` points at a list, so, like `pathConfigs`, it has no command-line option or environment variable. The scalar `enabled`, `file.path`, and `reconcileIntervalSecs` can also be set with `-D` overrides. On the proxy's [dashboard](https://prometheus-proxy.com/web-dashboard/index.md#the-paths-layout), each path is tagged `cfg` (static) or `disc` (discovered), so when a target is unexpectedly present or absent you can tell at a glance whether a human or the automation registered it. The [Basics Demo](https://prometheus-proxy.com/basics-demo/index.md#new-services-appear-without-a-restart) adds services to an agent's discovery file and takes them out again, and the [Kubernetes Demo](https://prometheus-proxy.com/kubernetes-demo/index.md#annotate-a-service-and-prometheus-scrapes-it) writes the file from annotated Services. ## Proxy Connection ```hocon agent { proxy { hostname = "proxy-host.example.com" // Proxy hostname port = 50051 // Proxy gRPC port } } ``` | Setting / CLI Option / Env Var | Default | Description | |:--------------------------------------------------------------------------------------------------------|:------------|:-----------------------------------------------------------------------| | [`agent.proxy.hostname`](https://prometheus-proxy.com/cli-reference/index.md#agent.proxy.hostname)
`--proxy, -p`
`PROXY_HOSTNAME` | "localhost" | The proxy's host, or `host:port`, used when `endpoints` is empty. `--proxy` and `PROXY_HOSTNAME` also take a comma-separated list, and replace `endpoints` ([below](#proxy-failover)) | | `agent.proxy.port` | 50051 | The proxy's port, and the port of an `endpoints` entry that names none | | `agent.proxy.endpoints` | [] | Proxies to fail over between, in order ([below](#proxy-failover)) | Or on the command line: ```bash java -jar prometheus-agent.jar \ --proxy proxy-host.example.com:50051 --config agent.conf ``` ### Proxy Failover For redundancy, give the agent an ordered list of proxy endpoints instead of a single hostname. It uses the first that accepts it, and moves to the next on a failed connect or when a proxy rejects its registration (or every one of its static paths, for a cause that can't clear); when a registered connection drops it returns to the head of the list, so a recovered primary is picked up on the next reconnect. Only one connection is active at a time. ```hocon agent { proxy { port = 50051 // For an entry that names no port endpoints = [ "proxy-a.example.com:50051", // Tried first "proxy-b.example.com:50051" // Used when proxy-a is unreachable ] } } ``` `--proxy` and `PROXY_HOSTNAME` accept the same list as a comma-separated value, and either one **replaces** `endpoints` entirely rather than adding to it: ```bash java -jar prometheus-agent.jar \ --proxy proxy-a.example.com:50051,proxy-b.example.com:50051 ``` A single value behaves exactly as it always has, so existing configurations need no change. `hostname` is used only when `endpoints` is empty; the two are never merged. An unparseable entry fails at startup rather than surfacing later as a connection error. !!! warning "All endpoints share one TLS configuration" The agent builds one TLS context and one authority override for the whole list, so its trust collection must hold every proxy's CA, and an `overrideAuthority` must be a name every proxy's certificate carries; otherwise the handshake fails with an opaque error rather than a clear configuration error. See [High Availability](https://prometheus-proxy.com/production/index.md#high-availability) for the Prometheus side: in particular, scrape an HA pair with `static_config`, never `http_sd_config`. The [Network Demo](https://prometheus-proxy.com/network-demo/index.md#the-primary-proxy-stops-and-the-agents-fail-over-to-the-standby) fails two agents over to a standby proxy when the primary stops, and again [when a link goes silent](https://prometheus-proxy.com/network-demo/index.md#a-link-goes-silent-the-agent-detects-it-and-fails-over). ## Agent Authentication If the proxy requires a [pre-shared agent token](https://prometheus-proxy.com/security/index.md#agent-authentication-pre-shared-token), set the matching value on the agent. It is presented as a gRPC metadata header on every call and is never logged. `--agent_token` overrides `AGENT_TOKEN`, which overrides `agent.agentToken`; empty, the default, sends no token. ```hocon agent { agentToken = "shared-secret" // Must match the proxy's proxy.agentToken } ``` ## gRPC Settings Configure the agent's gRPC connection to the proxy: ```hocon agent { grpc { keepAliveTimeSecs = -1 // -1 leaves gRPC's default: no PINGs keepAliveTimeoutSecs = 20 keepAliveWithoutCalls = false unaryDeadlineSecs = 30 } } ``` | Setting / CLI Option / Env Var | Default | Description | |:-------------------------------------------------------------------------------------------------------------------------------------------------------|:--------|:------------------------------------------------------------------------------------------------------------| | [`agent.grpc.keepAliveTimeSecs`](https://prometheus-proxy.com/cli-reference/index.md#agent.grpc.keepAliveTimeSecs)
`--keepalive_time_secs`
`KEEPALIVE_TIME_SECS` | INT_MAX | Seconds the connection goes quiet before the agent sends a PING | | [`agent.grpc.keepAliveTimeoutSecs`](https://prometheus-proxy.com/cli-reference/index.md#agent.grpc.keepAliveTimeoutSecs)
`--keepalive_timeout_secs`
`KEEPALIVE_TIMEOUT_SECS` | 20 | Seconds the agent waits for a PING's acknowledgment before closing the connection | | [`agent.grpc.keepAliveWithoutCalls`](https://prometheus-proxy.com/cli-reference/index.md#agent.grpc.keepAliveWithoutCalls)
`--keepalive_without_calls`
`KEEPALIVE_WITHOUT_CALLS` | false | Send PINGs while no call is open | | [`agent.grpc.unaryDeadlineSecs`](https://prometheus-proxy.com/cli-reference/index.md#agent.grpc.unaryDeadlineSecs)
`--unary_deadline_secs`
`UNARY_DEADLINE_SECS` | 30 | Seconds a single call to the proxy, such as a connect or a path's registration, may take; streams have none | A keepalive setting of `-1`, which the config file has unless you set it, leaves gRPC's default, the one the table gives. `INT_MAX` means the agent sends no PINGs. The proxy closes a connection whose PINGs come more often than its `proxy.grpc.permitKeepAliveTimeSecs`, 300 seconds by default, or that sends one while no call is open, unless its `proxy.grpc.permitKeepAliveWithoutCalls` is on, so set the agent's to match (see [gRPC Service](https://prometheus-proxy.com/configuration/proxy/index.md#grpc-service) and [gRPC Keepalive Tuning](https://prometheus-proxy.com/advanced/index.md#grpc-keepalive-tuning)). `unaryDeadlineSecs` is also how long a connect to a proxy whose host is gone, rather than refusing connections, takes to fail, before the agent tries again, or tries its next endpoint ([Proxy Failover](#proxy-failover)). A heartbeat's deadline is the shorter of it and `agent.internal.heartbeatMaxInactivitySecs` ([Internal Settings](#internal-settings)). ## Transport Filter Behind a reverse proxy such as nginx, disable the transport filter on each agent and on the proxy, since the proxy refuses an agent whose setting doesn't match the proxy's (see [Transport Filter](https://prometheus-proxy.com/configuration/proxy/index.md#transport-filter) and [nginx Reverse Proxy](https://prometheus-proxy.com/advanced/index.md#nginx-reverse-proxy)): ```hocon agent.transportFilterDisabled = true ``` | Setting / CLI Option / Env Var | Default | Description | |:-----------------------------------------------------------------------------------------------------------------------------------------------------|:--------|:----------------------------------------------------| | [`agent.transportFilterDisabled`](https://prometheus-proxy.com/cli-reference/index.md#agent.transportFilterDisabled)
`--tf-disabled, --tf_disabled`
`TRANSPORT_FILTER_DISABLED` | false | Disable the transport filter, as the proxy has done | ## HTTP Client Settings Configure how the agent makes HTTP requests to scrape endpoints: ```hocon agent { http { maxConcurrentClients = 5 clientTimeoutSecs = 30 maxContentLengthMBytes = 10 enableTrustAllX509Certificates = false trustStorePath = "" trustStorePassword = "" } } ``` | Setting / CLI Option / Env Var | Default | Description | |:--------------------------------------------------------------------------------------------------------------------------------------------------------------------|:--------|:----------------------------------------------------------------------------------------| | [`agent.http.maxConcurrentClients`](https://prometheus-proxy.com/cli-reference/index.md#agent.http.maxConcurrentClients)
`--max_concurrent_clients`
`MAX_CONCURRENT_CLIENTS` | 1 | Scrapes the agent runs at once | | [`agent.http.clientTimeoutSecs`](https://prometheus-proxy.com/cli-reference/index.md#agent.http.clientTimeoutSecs)
`--client_timeout_secs`
`CLIENT_TIMEOUT_SECS` | 90 | Seconds a request to a target may take | | [`agent.http.maxContentLengthMBytes`](https://prometheus-proxy.com/cli-reference/index.md#agent.http.maxContentLengthMBytes)
`--max_content_length_mbytes` | 10 | Largest scrape response, in megabytes | | [`agent.http.enableTrustAllX509Certificates`](https://prometheus-proxy.com/cli-reference/index.md#agent.http.enableTrustAllX509Certificates)
`--trust_all_x509`
`TRUST_ALL_X509_CERTIFICATES` | false | Skip certificate verification on HTTPS targets | | [`agent.http.trustStorePath`](https://prometheus-proxy.com/cli-reference/index.md#agent.http.trustStorePath)
`--https_truststore`
`HTTPS_TRUST_STORE_PATH` | "" | A JKS or PKCS12 trust store for HTTPS targets a private CA signed; empty uses the JDK's | | [`agent.http.trustStorePassword`](https://prometheus-proxy.com/cli-reference/index.md#agent.http.trustStorePassword)
`--https_truststore_password`
`HTTPS_TRUST_STORE_PASSWORD` | "" | The trust store's password | ### HTTP Client Cache The agent caches HTTP clients keyed by the basic auth credentials in a target's URL, if any. Configure cache behavior: ```hocon agent { http.clientCache { maxSize = 100 maxAgeMins = 30 maxIdleMins = 10 cleanupIntervalMins = 5 } } ``` | Setting / CLI Option / Env Var | Default | Description | |:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:--------|:---------------------------------| | [`agent.http.clientCache.maxSize`](https://prometheus-proxy.com/cli-reference/index.md#agent.http.clientCache.maxSize)
`--max_cache_size`
`MAX_CLIENT_CACHE_SIZE` | 100 | HTTP clients kept | | [`agent.http.clientCache.maxAgeMins`](https://prometheus-proxy.com/cli-reference/index.md#agent.http.clientCache.maxAgeMins)
`--max_cache_age_mins`
`MAX_CLIENT_CACHE_AGE_MINS` | 30 | Minutes a client is kept | | [`agent.http.clientCache.maxIdleMins`](https://prometheus-proxy.com/cli-reference/index.md#agent.http.clientCache.maxIdleMins)
`--max_cache_idle_mins`
`MAX_CLIENT_CACHE_IDLE_MINS` | 10 | Minutes an unused client is kept | | [`agent.http.clientCache.cleanupIntervalMins`](https://prometheus-proxy.com/cli-reference/index.md#agent.http.clientCache.cleanupIntervalMins)
`--cache_cleanup_interval_mins`
`CLIENT_CACHE_CLEANUP_INTERVAL_MINS` | 5 | Minutes between cleanups | ## Scraping HTTPS Endpoints For HTTPS scrape targets signed by a private or internal CA, point the agent at a trust store that contains that CA (`--https_truststore` / `HTTPS_TRUST_STORE_PATH` / `agent.http.trustStorePath`, with the matching `*_password`) so certificates are still validated. An empty path uses the JDK default trust store, and `--trust_all_x509` (which disables verification entirely) takes precedence. The trust store is loaded as the agent starts, so a missing file or a wrong password fails the agent's startup with an error naming `agent.http.trustStorePath`, rather than every scrape. See [Scraping HTTPS Endpoints](https://prometheus-proxy.com/security/index.md#scraping-https-endpoints) for details. ## Scrape Settings ```hocon agent { scrapeTimeoutSecs = 15 scrapeMaxRetries = 0 chunkContentSizeKbs = 32 minGzipSizeBytes = 512 } ``` | Setting / CLI Option / Env Var | Default | Description | |:----------------------------------------------------------------------------------------------------------------------|:--------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [`agent.scrapeTimeoutSecs`](https://prometheus-proxy.com/cli-reference/index.md#agent.scrapeTimeoutSecs)
`--timeout`
`SCRAPE_TIMEOUT_SECS` | 15 | Total time allowed for a scrape including retries; a shorter Prometheus scrape timeout wins, and the agent sends whichever applies to the target in `X-Prometheus-Scrape-Timeout-Seconds` | | [`agent.scrapeMaxRetries`](https://prometheus-proxy.com/cli-reference/index.md#agent.scrapeMaxRetries)
`--max_retries`
`SCRAPE_MAX_RETRIES` | 0 | Maximum retries; 0 disables retries | | [`agent.chunkContentSizeKbs`](https://prometheus-proxy.com/cli-reference/index.md#agent.chunkContentSizeKbs)
`--chunk`
`CHUNK_CONTENT_SIZE_KBS` | 32 | Gzipped result chunked at this size; at most 4032 | | [`agent.minGzipSizeBytes`](https://prometheus-proxy.com/cli-reference/index.md#agent.minGzipSizeBytes)
`--gzip`
`MIN_GZIP_SIZE_BYTES` | 512 | Gzip-compressed above this; at most 4128768 | !!! note "Text exposition formats only" The agent and proxy carry a scrape as text, so the agent asks targets only for the text and OpenMetrics formats: it drops the protobuf entry from the `Accept` header Prometheus sends. With native histograms enabled, Prometheus asks for protobuf first; through the proxy it receives the text format instead, and native histograms aren't available. Classic histograms are unaffected. ## Metric Filtering The agent-to-proxy hop is usually the expensive one, over a WAN link, metered egress, or a constrained tunnel, yet filtering with Prometheus `metric_relabel_configs` discards data only *after* it has crossed it. Filtering at the agent drops unwanted metric families before they are sent, and it runs before the payload is gzipped and chunked, so the saving composes with `chunkContentSizeKbs` and `minGzipSizeBytes` above. Filters are declared in a top-level `agent.filters` list, keyed by `path` rather than nested inside `pathConfigs`: ```hocon agent { pathConfigs: [ { name: "app1" path: "app1_metrics" url: "http://app1:9090/metrics" } ] // Drop Go runtime GC metrics for app1 before they cross the WAN. // Regexes are fully anchored, matching Prometheus relabel_config semantics: // "go_" matches nothing; "go_.*" matches go_gc_duration_seconds. filters: [ { path: "app1_metrics" metricNameAllow: [] metricNameDeny: [ "go_gc_.*", "go_memstats_.*" ] } ] } ``` | Field | Required | Description | |:------------------|:---------|:----------------------------------------------------------------| | `path` | Yes | The `pathConfigs` (or discovered) path this filter applies to | | `metricNameAllow` | Yes | Fully-anchored regexes; an empty list allows every family | | `metricNameDeny` | Yes | Fully-anchored regexes; evaluated after `metricNameAllow` | Both list fields must be present on every element, so a filter that only denies writes `metricNameAllow: []`. The default is `filters: []`, no filtering, so an existing config with no `filters` key loads unchanged. **Regexes are fully anchored** (`Regex.matches()`), as Prometheus's `relabel_config` and `metric_relabel_configs` match: `deny: [ "go_" ]` matches nothing, and it takes `deny: [ "go_.*" ]` to match `go_goroutines`. **Matching is against the metric family, not each series.** A histogram's `_bucket`, `_sum`, and `_count` series are always kept or dropped together, along with the family's metadata lines. One consequence worth knowing: once a family is open, a series-level rule such as `metricNameDeny: [ "http_req_duration_seconds_bucket" ]` is a silent no-op, since the `_bucket` lines take the family's decision rather than being matched themselves. ??? info "How each line is matched" A `# HELP` or `# TYPE` line, or `# UNIT` in OpenMetrics, opens a family, and whether it's allowed or denied is decided once, against the family's name. Every sample line that belongs to the family, by the exact name or the name plus a histogram's, a summary's, or an OpenMetrics suffix (`_bucket`, `_sum`, `_count`, `_created`, `_total`, `_gsum`, `_gcount`, `_info`), takes that decision instead of being matched again. A sample line with no open family, as in a payload with no `TYPE` lines at all, is matched on its full name. A name outside the legacy character set, which Prometheus 3 targets write quoted (`# TYPE "http.requests" counter`, and `{"http.requests",method="GET"} 3`), is matched without its quotes or escapes, so `metricNameAllow: [ "http\\.requests" ]` matches it. **An empty `metricNameAllow` allows everything.** `metricNameDeny` is applied *after* allow, so deny wins on overlap. To make family scoping concrete, given this filter: ```hocon { path: "app1_metrics", metricNameAllow: [], metricNameDeny: [ "go_.*" ] } ``` a scraped payload is transformed like this: === "Scraped from the target" ``` # HELP go_goroutines Number of goroutines # TYPE go_goroutines gauge go_goroutines 12 # HELP http_req_duration_seconds Request duration # TYPE http_req_duration_seconds histogram http_req_duration_seconds_bucket{le="0.1"} 5 http_req_duration_seconds_bucket{le="+Inf"} 9 http_req_duration_seconds_sum 3.2 http_req_duration_seconds_count 9 ``` === "Sent to the proxy" ``` # HELP http_req_duration_seconds Request duration # TYPE http_req_duration_seconds histogram http_req_duration_seconds_bucket{le="0.1"} 5 http_req_duration_seconds_bucket{le="+Inf"} 9 http_req_duration_seconds_sum 3.2 http_req_duration_seconds_count 9 ``` The `go_goroutines` family goes entirely, `# HELP` and `# TYPE` lines included. The histogram is untouched: `deny` never matched it, and its `_bucket`, `_sum`, and `_count` series are evaluated as one family rather than one by one, which is what keeps a filter from delivering a histogram with some of its series missing. !!! note "Fails open on payloads it can't safely filter" A body with a `Content-Type` that isn't text, such as protobuf or an HTML error page, passes through unfiltered. A body that is not valid UTF-8 also passes through unfiltered and byte-exact rather than risk corrupting it. Each logs a warning once per path. The worst that can happen is bandwidth not saved, never a corrupted payload. Filters apply by path to both statically configured paths and paths added by [dynamic discovery](#dynamic-target-discovery); a filter's `path` is matched the same way regardless of which route registered it. An invalid regex fails agent startup rather than surfacing later at scrape time. !!! tip "Confirming a filter attached" A filter whose `path` matches no registered path says nothing: it never runs. The agent's registration log line for each path reports whether a filter attached: ```text Registered http://app1:9090/metrics as /app1_metrics with labels {} (static) with a metric filter ``` If the line for your path does not end with `with a metric filter`, the `path` in your `filters` entry does not match the registered path. The `agent_filter_*` counters below are the other way to tell: they are only ever created for paths whose filter actually ran. Three counters, each labeled by `launch_id` and `path`, track filtering and are only created for paths that actually have a filter configured: | Metric | Labels | Description | |:-----------------------------------|:------------------------------|:---------------------------------------------| | `agent_filter_lines_dropped_total` | `launch_id`, `path` | Exposition lines dropped by the filter | | `agent_filter_bytes_saved_total` | `launch_id`, `path` | Bytes removed from the payload by the filter | | `agent_filter_fail_open_total` | `launch_id`, `path`, `reason` | Scrapes let through unfiltered, by reason | A filter can't drop labels (there's no `dropLabels`), rename or relabel metrics, or apply to every path at once: each filter belongs to one path. The [Network Demo](https://prometheus-proxy.com/network-demo/index.md#a-low-bandwidth-link-fails-scrapes-filtering-at-the-agent-fixes-it) drops a metric family no one uses, so a large payload fits a thin link inside Prometheus's timeout. ## Consolidated Mode By default, each path is owned by a single agent. Enable consolidated mode to allow multiple agents to register the same path: ```hocon agent { consolidated = true // Allow multiple agents per path proxy.hostname = "proxy-host.example.com" pathConfigs: [ { name: "Shared metrics" path: shared_metrics url: "http://localhost:9100/metrics" } ] } ``` Also set with [`--consolidated`](https://prometheus-proxy.com/cli-reference/index.md#agent.consolidated) or `CONSOLIDATED=true`. Give each agent a separate instance of the service to scrape. [Consolidated Mode](https://prometheus-proxy.com/advanced/index.md#consolidated-mode) explains how the proxy merges their answers, and why agents that scrape the same endpoint send each series twice. ## Agent Naming Give agents descriptive names for easier identification in logs and metrics: ```bash java -jar prometheus-agent.jar --name production-agent-01 --config agent.conf ``` Or with `AGENT_NAME`, or in the config file: ```hocon agent.name = "production-agent-01" ``` If no name is provided, the agent uses `Unnamed-`. ## Admin Endpoints Enable admin endpoints for health checks and debugging: ```hocon agent { admin { enabled = true port = 8093 pingPath = "ping" versionPath = "version" healthCheckPath = "healthcheck" threadDumpPath = "threaddump" debugEnabled = false } } ``` | Setting / CLI Option / Env Var | Default | Description | |:---------------------------------------------------------------------------------------------------------------|:--------------|:------------------------------------------| | [`agent.admin.enabled`](https://prometheus-proxy.com/cli-reference/index.md#agent.admin.enabled)
`--admin, -r`
`ADMIN_ENABLED` | false | Serve the endpoints below | | [`agent.admin.port`](https://prometheus-proxy.com/cli-reference/index.md#agent.admin.port)
`--admin_port, -i`
`ADMIN_PORT` | 8093 | Their port | | `agent.admin.pingPath` | "ping" | The ping endpoint's path | | `agent.admin.versionPath` | "version" | The version endpoint's path | | `agent.admin.healthCheckPath` | "healthcheck" | The health check endpoint's path | | `agent.admin.threadDumpPath` | "threaddump" | The thread dump endpoint's path | | [`agent.admin.debugEnabled`](https://prometheus-proxy.com/cli-reference/index.md#agent.admin.debugEnabled)
`--debug, -b`
`DEBUG_ENABLED` | false | Serve `/debug`, the agent's state as text | When enabled, the following endpoints are available: | Endpoint | Description | |:-------------------|:--------------------------------------------------| | `GET /ping` | Returns "pong" (liveness check) | | `GET /healthcheck` | Returns health status JSON | | `GET /version` | Returns version information | | `GET /threaddump` | Returns JVM thread dump | | `GET /debug` | Agent debug info (requires `debugEnabled = true`) | `/healthcheck` reports the agent's state, not its connection: it stays healthy while the agent can't reach a proxy, and turns unhealthy once `agent.internal.scrapeRequestBacklogUnhealthySize` scrape requests wait for the agent ([Internal Settings](#internal-settings)). The admin port answers on every interface without authentication, so keep it on an internal network. [Admin and Debug Endpoints](https://prometheus-proxy.com/embedded-debugging/index.md#admin-and-debug-endpoints) says what each endpoint shows, and the [Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md#debugging-the-agent) calls each one. ## Dashboard The agent can serve a direct agent dashboard, on a separate port, off unless turned on: its connection to the proxy, each path and why the proxy refused one, each path's recent scrapes and a Scrape now button, its filters, discovery, settings, and what has happened to it. A proxy can also show it as a relayed agent dashboard, through the agent's connection, unless `showOnProxy` is `false`. See [Agent Dashboard](https://prometheus-proxy.com/agent-dashboard/index.md). ```hocon agent { dashboard { enabled = true port = 8095 host = "127.0.0.1" // Keeps it on the agent's host password = "" // Requires a login; better set as DASHBOARD_PASSWORD } } ``` | Setting / CLI Option / Env Var | Default | Description | |:-----------------------------------------------------------------------------------------------------------------|:------------|:----------------------------------------------------------------------------------| | [`agent.dashboard.enabled`](https://prometheus-proxy.com/cli-reference/index.md#agent.dashboard.enabled)
`--dashboard`
`DASHBOARD_ENABLED` | false | Serve the agent's direct dashboard | | [`agent.dashboard.port`](https://prometheus-proxy.com/cli-reference/index.md#agent.dashboard.port)
`--dashboard_port`
`DASHBOARD_PORT` | 8095 | Its port | | [`agent.dashboard.path`](https://prometheus-proxy.com/cli-reference/index.md#agent.dashboard.path)
`--dashboard_path`
`DASHBOARD_PATH` | "dashboard" | Its base path | | [`agent.dashboard.host`](https://prometheus-proxy.com/cli-reference/index.md#agent.dashboard.host)
`--dashboard_host`
`DASHBOARD_HOST` | "0.0.0.0" | The address it listens on; `"127.0.0.1"` keeps it on the agent's host | | [`agent.dashboard.username`](https://prometheus-proxy.com/cli-reference/index.md#agent.dashboard.username)
`DASHBOARD_USERNAME` | "admin" | The login's username, once a password is set | | [`agent.dashboard.password`](https://prometheus-proxy.com/cli-reference/index.md#agent.dashboard.password)
`DASHBOARD_PASSWORD` | | Requires a login, from the login page or as Basic Auth; empty leaves it open | | `agent.dashboard.refreshIntervalSecs` | 2 | Seconds between pushes of values that drift rather than change, such as uptime | | `agent.dashboard.pathHistorySize` | 20 | Scrapes kept per path, for its history strip and Recent scrapes | | `agent.dashboard.scrapeNowEnabled` | true | A Scrape now button on each path, which scrapes its target from the agent at once | | `agent.dashboard.activityLogSize` | 500 | Lines kept in the Activity view | | `agent.dashboard.maxSessions` | 50 | Open WebSocket sessions; more are closed | | `agent.dashboard.allowedOrigins` | [] | Browser origins allowed besides the dashboard's host | | `agent.dashboard.allowedHosts` | [] | Host names the dashboard answers to; empty turns the check off | | `agent.dashboard.trustedProxies` | [] | Reverse proxies whose `X-Forwarded-For` gives the client's address | | `agent.dashboard.framingEnabled` | true | Lets any web page show the dashboard in a frame; false refuses framing | | `agent.dashboard.showOnProxy` | true | Lets a proxy with `proxy.dashboard.agentScreens` on show this agent's relayed dashboard, whether or not its direct one is on | ## Metrics The agent's own metrics, the `agent_*` series the [Agents dashboard](../grafana.md#dashboards) reads, are off unless turned on, on a separate metrics port, at a path of the proxy's, or both: ```hocon agent { metrics { enabled = true port = 8083 // Since 4.7.0: served through the proxy at /east_agent_metrics proxyPath = east_agent_metrics proxyPathLabels = "{\"region\": \"east\"}" } } ``` | Setting / CLI Option / Env Var | Default | Description | |:---------------------------------------------------------------------------------------------------------------------------|:----------|:---------------------------------------------------------------------------------| | [`agent.metrics.enabled`](https://prometheus-proxy.com/cli-reference/index.md#agent.metrics.enabled)
`--metrics, -e`
`METRICS_ENABLED` | false | Serve the agent's metrics on a separate port | | [`agent.metrics.port`](https://prometheus-proxy.com/cli-reference/index.md#agent.metrics.port)
`--metrics_port, -m`
`METRICS_PORT` | 8083 | Their port | | `agent.metrics.path` | "metrics" | Their path on that port | | [`agent.metrics.proxyPath`](https://prometheus-proxy.com/cli-reference/index.md#agent.metrics.proxyPath)
`--metrics_proxy_path`
`METRICS_PROXY_PATH` | "" | A proxy path the agent serves its metrics at, read in-process; empty serves none | | `agent.metrics.proxyPathLabels` | "{}" | The proxy path's service discovery labels, as JSON | Prometheus, outside the firewall, reaches the agent's metrics only through the proxy, so the proxy path is all most agents need. The port suits a scraper on the agent's network, which can read the agent while it can't reach the proxy. A standalone agent serves the same metrics at either, its JVM metrics included (`standardExportsEnabled` and the rest). See [Monitoring](https://prometheus-proxy.com/monitoring/index.md#port-or-proxy-path) for when each fits. Agents that share a config file each need a separate path (see [Scraping Internal Metrics](https://prometheus-proxy.com/monitoring/index.md#scraping-internal-metrics)). ## Internal Settings Configure reconnects, retries, heartbeats, and the health check's threshold. These settings have no command-line option or environment variable: set them in the config file, or with `-D`, as `-Dagent.internal.reconnectPauseSecs=5`. ```hocon agent { internal { reconnectPauseSecs = 3 // Seconds between connect attempts rejectedPathRetrySecs = 10 // First wait before retrying a refused path rejectedPathRetryMaxSecs = 300 // Longest wait between retries heartbeatMaxInactivitySecs = 5 // Quiet seconds before a heartbeat } } ``` | Setting | Default | Description | |:---------------------------------------------------|:--------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------| | `agent.internal.reconnectPauseSecs` | 3 | Seconds between attempts to connect to the proxy | | `agent.internal.rejectedPathRetrySecs` | 10 | Seconds before the agent retries a static path the proxy refused for a cause that can clear, or reclaims one another agent took over; doubles with each refusal | | `agent.internal.rejectedPathRetryMaxSecs` | 300 | Longest wait between those retries, and a discovered path's | | `agent.internal.heartbeatEnabled` | true | Send a heartbeat when the connection goes quiet | | `agent.internal.heartbeatMaxInactivitySecs` | 5 | Seconds the connection goes quiet before a heartbeat | | `agent.internal.heartbeatCheckPauseMillis` | 500 | Milliseconds between checks for a quiet connection | | `agent.internal.scrapeRequestBacklogUnhealthySize` | 25 | Scrape requests waiting for the agent that mark it unhealthy; its queue holds twice this | | `agent.internal.cioTimeoutSecs` | 90 | Deprecated for `agent.http.clientTimeoutSecs`; used only when changed while that stays at its default | A heartbeat keeps the proxy from evicting a quiet agent as inactive (`proxy.internal.maxAgentInactivitySecs`, 60 seconds by default), and finds a connection that died: after three failed heartbeats in a row, the agent drops the connection and reconnects. `reconnectPauseSecs`, `rejectedPathRetrySecs`, `rejectedPathRetryMaxSecs`, `heartbeatCheckPauseMillis`, and `scrapeRequestBacklogUnhealthySize` must be more than zero, or the agent fails at startup. `agent.internal.zipkin` sends traces of the agent's scrapes and gRPC calls to Zipkin, off by default; see [Zipkin Tracing](https://prometheus-proxy.com/advanced/index.md#zipkin-tracing). ## Log Level ```hocon // Set log level in config file: proxy.logLevel = "debug" agent.logLevel = "debug" // Or via CLI: // java -jar prometheus-proxy.jar --log_level debug // java -jar prometheus-agent.jar --log_level debug // Or via environment variable: // PROXY_LOG_LEVEL=debug // AGENT_LOG_LEVEL=debug // Available levels: trace, debug, info, warn, error, off ``` Unset, a standalone agent logs at `info`; an embedded agent's loggers follow its application's logging (see [Logging](https://prometheus-proxy.com/embedded-debugging/index.md#logging)). ## Full Example [`examples/agent.conf`](https://prometheus-proxy.com/examples/index.md#production-agent-agentconf) is a starting point for an agent's config file: the Quick Start's proxy and endpoint, and the settings the [Pre-Flight Checklist](https://prometheus-proxy.com/production/index.md#pre-flight-checklist) asks for, each with the section that explains it: ```hocon // A starting point for an agent: the Quick Start's two settings, the proxy and one endpoint, and the agent's side of // Running in Production's Pre-Flight Checklist, each with the page that explains it. Keep only what you need; // config/config.conf describes every setting. // https://prometheus-proxy.com/production/#pre-flight-checklist // // Secrets stay out of the file: the agent reads its token from AGENT_TOKEN, and a direct agent dashboard's password // from DASHBOARD_PASSWORD, which take precedence over a config file. agent { // How the agent appears in the proxy's dashboard, its logs, and its metrics; unset, the agent names itself after // its host: https://prometheus-proxy.com/configuration/agent/#agent-naming // // name = "my-agent" // The proxy this agent connects to, on port 50051 unless the address names another. With a standby proxy, list // both in endpoints instead, in failover order: https://prometheus-proxy.com/configuration/agent/#proxy-connection proxy.hostname = "proxy-host.example.com" // proxy.endpoints = ["proxy-host.example.com:50051", "standby-host.example.com:50051"] // Each entry serves one endpoint: Prometheus scrapes its path on the proxy, and the agent fetches its url. Its // labels, as JSON, are the labels Prometheus service discovery gives the path: // https://prometheus-proxy.com/configuration/agent/#path-configs pathConfigs: [ { name: "My App metrics" path: my_app_metrics url: "http://localhost:9100/metrics" // labels: """{"job": "my-app"}""" } ] // Paths from a file the agent watches, which it adds and removes without a restart: // https://prometheus-proxy.com/configuration/agent/#dynamic-target-discovery // // discovery { // enabled = true // file.path = "/etc/prometheus-agent/targets.conf" // } // TLS to the proxy: the CA that signed the proxy's certificate, and, for a proxy that requires mutual TLS, the // agent's certificate and key: https://prometheus-proxy.com/security/tls/ // // tls { // trustCertCollectionFilePath = "/etc/prometheus-agent/tls/ca.crt" // certChainFilePath = "/etc/prometheus-agent/tls/agent.crt" // privateKeyFilePath = "/etc/prometheus-agent/tls/agent.key" // } // Admin endpoints on port 8093, for health checks: /ping for liveness, and /healthcheck for readiness. // https://prometheus-proxy.com/monitoring/#admin-endpoints admin { enabled = true port = 8093 } // The agent's metrics, which the proxy serves at /agent_metrics, read in-process, with no port to open: // https://prometheus-proxy.com/monitoring/ metrics.proxyPath = agent_metrics // The agent's dashboard. A proxy with agentScreens on shows it as a relayed agent dashboard, through the agent's // connection, unless showOnProxy is false. A direct agent dashboard serves it on port 8095 of this host too, with // its login from DASHBOARD_PASSWORD: // https://prometheus-proxy.com/agent-dashboard/#direct-and-relayed-agent-dashboards dashboard { showOnProxy = true // enabled = true // port = 8095 // host = "127.0.0.1" } } ``` The same directory has more: - [`examples/simple.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/examples/simple.conf) has the proxy and the agent monitor themselves, the agent serving the proxy's metrics and its own through the proxy. - [`examples/myapps.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/examples/myapps.conf) scrapes several endpoints. - [`examples/federate.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/examples/federate.conf) scrapes a Prometheus server's federation endpoint. - [`examples/discovery-targets.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/examples/discovery-targets.conf) is a [dynamic discovery](#dynamic-target-discovery) targets file, which the agent watches rather than reads with `--config`. ## Full Reference See the complete configuration schema: [`config/config.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/config/config.conf) --- Source: https://prometheus-proxy.com/configuration/proxy/ # Proxy Configuration The proxy runs outside the firewall alongside Prometheus. It accepts scrape requests from Prometheus on HTTP and communicates with agents via gRPC. The settings below are keys in the proxy's config file. Each section's table gives a key over its command-line option and environment variable, where it has them, and links the key to its row in the [CLI Reference](https://prometheus-proxy.com/cli-reference/index.md#proxy-options). A key with neither is set in the config file, or with `-D`. | Section | Covers | |:---------------------------------------------------|:-----------------------------------------------------------------------------------------------------| | [HTTP Service](#http-service) | `proxy.http`: the port Prometheus scrapes | | [gRPC Service](#grpc-service) | `proxy.agent.port` and `proxy.grpc`: the port agents connect to, its keepalives, and its time limits | | [Agent Authentication](#agent-authentication) | `proxy.agentToken`: one token every agent presents | | [Per-Agent Identities](#per-agent-identities) | `proxy.auth`: each identity's token, and the paths it may register | | [Prometheus Service Discovery](#service-discovery) | `proxy.service.discovery`: where Prometheus finds the paths | | [Admin Endpoints](#admin-endpoints) | `proxy.admin`: ping, health check, and debug endpoints | | [Dashboard](#dashboard) | `proxy.dashboard`: the dashboard, its login, and the screens page | | [Metrics](#metrics) | `proxy.metrics`: the proxy's own metrics | | [Internal Settings](#internal-settings) | `proxy.internal`: agent eviction, scrape limits, and what agents may register | | [Content Size Limits](#content-size-limits) | The largest result the proxy takes, zipped and unzipped | | [Transport Filter](#transport-filter) | `proxy.transportFilterDisabled`, behind a reverse proxy | | [gRPC Reflection](#grpc-reflection) | `proxy.reflectionDisabled` | | [Log Level](#log-level) | `proxy.logLevel` | | [Full Example](#full-example) | A starting point for a proxy's config file | | [Full Reference](#full-reference) | Every setting with its default | ## HTTP Service Configure the HTTP service that Prometheus scrapes: ```hocon proxy { http { port = 8080 host = "0.0.0.0" idleTimeoutSecs = 45 requestLoggingEnabled = true } } ``` | Setting / CLI Option / Env Var | Default | Description | |:-----------------------------------------------------------------------------------------|:----------|:------------------------------------------------------| | [`proxy.http.port`](https://prometheus-proxy.com/cli-reference/index.md#proxy.http.port)
`--port, -p`
`PROXY_PORT` | 8080 | The port Prometheus scrapes | | `proxy.http.host` | "0.0.0.0" | The address the scrape port listens on | | `proxy.http.idleTimeoutSecs` | 45 | Seconds an idle connection from Prometheus stays open | | `proxy.http.requestLoggingEnabled` | true | Log each request the scrape port answers | `proxy.http.idleTimeoutSecs` is how long the proxy keeps an idle connection from Prometheus open. `-1` gives the default, 45 seconds. `0` doesn't turn the timeout off: it, and any other negative value, fails the proxy's startup, since the scrape port would close every connection before answering it. ## gRPC Service Configure the gRPC service that agents connect to: ```hocon proxy { agent.port = 50051 grpc { keepAliveTimeSecs = 7200 keepAliveTimeoutSecs = 20 permitKeepAliveWithoutCalls = false maxConnectionIdleSecs = -1 maxConnectionAgeSecs = -1 } } ``` | Setting / CLI Option / Env Var | Default | Description | |:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:--------|:----------------------------------------------------------------------------------------------------| | [`proxy.agent.port`](https://prometheus-proxy.com/cli-reference/index.md#proxy.agent.port)
`--agent_port, -a`
`AGENT_PORT` | 50051 | The port agents connect to | | [`proxy.grpc.handshakeTimeoutSecs`](https://prometheus-proxy.com/cli-reference/index.md#proxy.grpc.handshakeTimeoutSecs)
`--handshake_timeout_secs`
`HANDSHAKE_TIMEOUT_SECS` | 120 | Seconds a new connection has to finish its handshake | | [`proxy.grpc.keepAliveTimeSecs`](https://prometheus-proxy.com/cli-reference/index.md#proxy.grpc.keepAliveTimeSecs)
`--keepalive_time_secs`
`KEEPALIVE_TIME_SECS` | 7200 | Seconds a connection goes quiet before the proxy sends a PING | | [`proxy.grpc.keepAliveTimeoutSecs`](https://prometheus-proxy.com/cli-reference/index.md#proxy.grpc.keepAliveTimeoutSecs)
`--keepalive_timeout_secs`
`KEEPALIVE_TIMEOUT_SECS` | 20 | Seconds the proxy waits for a PING's acknowledgment before closing the connection | | [`proxy.grpc.permitKeepAliveWithoutCalls`](https://prometheus-proxy.com/cli-reference/index.md#proxy.grpc.permitKeepAliveWithoutCalls)
`--permit_keepalive_without_calls`
`PERMIT_KEEPALIVE_WITHOUT_CALLS` | false | Accept an agent's PINGs while it has no call open | | [`proxy.grpc.permitKeepAliveTimeSecs`](https://prometheus-proxy.com/cli-reference/index.md#proxy.grpc.permitKeepAliveTimeSecs)
`--permit_keepalive_time_secs`
`PERMIT_KEEPALIVE_TIME_SECS` | 300 | Shortest interval between an agent's PINGs the proxy accepts; PINGs more often close the connection | | [`proxy.grpc.maxConnectionIdleSecs`](https://prometheus-proxy.com/cli-reference/index.md#proxy.grpc.maxConnectionIdleSecs)
`--max_connection_idle_secs`
`MAX_CONNECTION_IDLE_SECS` | INT_MAX | Seconds a connection with no call open stays before the proxy closes it | | [`proxy.grpc.maxConnectionAgeSecs`](https://prometheus-proxy.com/cli-reference/index.md#proxy.grpc.maxConnectionAgeSecs)
`--max_connection_age_secs`
`MAX_CONNECTION_AGE_SECS` | INT_MAX | Seconds a connection lasts before the proxy closes it gracefully | | [`proxy.grpc.maxConnectionAgeGraceSecs`](https://prometheus-proxy.com/cli-reference/index.md#proxy.grpc.maxConnectionAgeGraceSecs)
`--max_connection_age_grace_secs`
`MAX_CONNECTION_AGE_GRACE_SECS` | INT_MAX | Seconds a connection past its age has to finish its calls | A gRPC setting of `-1`, which the config file has unless you set it, leaves gRPC's default, the one the table gives. `INT_MAX` means no limit. ## Agent Authentication The agent gRPC port is unauthenticated by default. Set a [pre-shared token](https://prometheus-proxy.com/security/index.md#agent-authentication-pre-shared-token) so the proxy rejects agents that do not present a matching value (`UNAUTHENTICATED`). `--agent_token` overrides `AGENT_TOKEN`, which overrides `proxy.agentToken`. Empty, the default, turns the check off unless `proxy.auth` (below) is set, and the proxy then logs a startup warning unless `proxy.auth` or mutual TLS is configured. The token is never logged. ```hocon proxy { agentToken = "shared-secret" // Agents must present the same value } ``` ## Per-Agent Identities Scope agents to specific paths with `proxy.auth`: a list of named identities, each with a token and allowed path glob patterns. The proxy resolves an agent's token to an identity and rejects any `registerPath` for a path that does not match the identity's patterns. An empty `paths` list allows all paths. A pattern loses one leading `/`, as a path does, and one with a `/` left after it fails startup. A legacy `proxy.agentToken` (above) is honored alongside `auth` as an allow-all identity, which eases migration. See [Per-Agent Identities and Path Authorization](https://prometheus-proxy.com/security/index.md#per-agent-identities-and-path-authorization) for details and a migration walkthrough. ```hocon proxy { auth = [ { name = team-a, token = "team-a-token", paths = ["team_a_*"] } { name = team-b, token = "team-b-token", paths = ["team_b_*"] } ] } ``` Because `auth` is a list of objects, it can only be set in a config file: it has no command-line option or environment variable, and the `-D` override can't express a list. Identity names must be unique, and tokens non-empty and unique, the legacy `proxy.agentToken` included. The name `legacy-agent-token` is reserved for the legacy `proxy.agentToken`, which the logs name that way and the dashboard shows as *shared token*, so the proxy refuses to start with an entry of that name, whether or not `proxy.agentToken` is set. ## Prometheus Service Discovery { #service-discovery } Enable Prometheus HTTP service discovery: ```hocon proxy { service.discovery { enabled = true path = "discovery" targetPrefix = "proxy-host.example.com:8080" } } ``` | Setting / CLI Option / Env Var | Default | Description | |:-------------------------------------------------------------------------------------------------------------------------------------------------|:-----------------|:---------------------------------------------------------------------------------------------------------| | [`proxy.service.discovery.enabled`](https://prometheus-proxy.com/cli-reference/index.md#proxy.service.discovery.enabled)
`--sd_enabled`
`SD_ENABLED` | false | Serve Prometheus's HTTP service discovery | | [`proxy.service.discovery.path`](https://prometheus-proxy.com/cli-reference/index.md#proxy.service.discovery.path)
`--sd_path`
`SD_PATH` | "discovery" | The path it's served at, with at most one leading `/` | | [`proxy.service.discovery.targetPrefix`](https://prometheus-proxy.com/cli-reference/index.md#proxy.service.discovery.targetPrefix)
`--sd_target_prefix`
`SD_TARGET_PREFIX` | "localhost:8080" | Each target's address: the proxy's `host:port` as Prometheus reaches it, or an `http(s)` URL | | `proxy.service.discovery.reserveJobAndInstanceLabels` | false | Also drop the `job` and `instance` labels an agent gives a path; labels starting `__` are always dropped | See [Prometheus Service Discovery](https://prometheus-proxy.com/service-discovery/index.md) for complete details. ## Admin Endpoints Enable admin endpoints for health checks and debugging: ```hocon proxy { admin { enabled = true port = 8092 pingPath = "ping" versionPath = "version" healthCheckPath = "healthcheck" threadDumpPath = "threaddump" debugEnabled = false } } ``` | Setting / CLI Option / Env Var | Default | Description | |:---------------------------------------------------------------------------------------------------------------|:--------------|:------------------------------------------| | [`proxy.admin.enabled`](https://prometheus-proxy.com/cli-reference/index.md#proxy.admin.enabled)
`--admin, -r`
`ADMIN_ENABLED` | false | Serve the endpoints below | | [`proxy.admin.port`](https://prometheus-proxy.com/cli-reference/index.md#proxy.admin.port)
`--admin_port, -i`
`ADMIN_PORT` | 8092 | Their port | | `proxy.admin.pingPath` | "ping" | The ping endpoint's path | | `proxy.admin.versionPath` | "version" | The version endpoint's path | | `proxy.admin.healthCheckPath` | "healthcheck" | The health check endpoint's path | | `proxy.admin.threadDumpPath` | "threaddump" | The thread dump endpoint's path | | [`proxy.admin.debugEnabled`](https://prometheus-proxy.com/cli-reference/index.md#proxy.admin.debugEnabled)
`--debug, -b`
`DEBUG_ENABLED` | false | Serve `/debug`, the proxy's state as text | | `proxy.admin.recentRequestsQueueSize` | 50 | Recent requests `/debug` lists | When enabled, the following endpoints are available: | Endpoint | Description | |:-------------------|:--------------------------------------------------| | `GET /ping` | Returns "pong" (liveness check) | | `GET /healthcheck` | Returns health status JSON | | `GET /version` | Returns version information | | `GET /threaddump` | Returns JVM thread dump | | `GET /debug` | Proxy debug info (requires `debugEnabled = true`) | ## Dashboard The proxy can serve an operational dashboard on a separate port. It's off by default. ```hocon proxy { dashboard { enabled = true port = 8094 host = "127.0.0.1" // Keeps it on the proxy's host password = "" // Requires a login; better set as DASHBOARD_PASSWORD } } ``` | Setting / CLI Option / Env Var | Default | Description | |:-----------------------------------------------------------------------------------------------------------------|:------------|:---------------------------------------------------------------------------------------------------| | [`proxy.dashboard.enabled`](https://prometheus-proxy.com/cli-reference/index.md#proxy.dashboard.enabled)
`--dashboard`
`DASHBOARD_ENABLED` | false | Serve the dashboard | | [`proxy.dashboard.port`](https://prometheus-proxy.com/cli-reference/index.md#proxy.dashboard.port)
`--dashboard_port`
`DASHBOARD_PORT` | 8094 | Its port, not the admin port | | [`proxy.dashboard.path`](https://prometheus-proxy.com/cli-reference/index.md#proxy.dashboard.path)
`--dashboard_path`
`DASHBOARD_PATH` | "dashboard" | Its base path, as in `http://:8094/dashboard` | | [`proxy.dashboard.host`](https://prometheus-proxy.com/cli-reference/index.md#proxy.dashboard.host)
`--dashboard_host`
`DASHBOARD_HOST` | "0.0.0.0" | The address it listens on; `"127.0.0.1"` keeps it on the proxy's host | | [`proxy.dashboard.username`](https://prometheus-proxy.com/cli-reference/index.md#proxy.dashboard.username)
`DASHBOARD_USERNAME` | "admin" | The login's username, once a password is set | | [`proxy.dashboard.password`](https://prometheus-proxy.com/cli-reference/index.md#proxy.dashboard.password)
`DASHBOARD_PASSWORD` | | Requires a login, from the login page or as Basic Auth; empty leaves it open | | `proxy.dashboard.refreshIntervalSecs` | 2 | Seconds between pushes of values that drift rather than change, such as backlogs | | `proxy.dashboard.pathHistorySize` | 20 | Scrapes kept per path, for the History column and each agent's Recent scrapes | | `proxy.dashboard.departedPathRetentionSecs` | 3600 | Seconds a path whose agent has gone stays in the path table | | `proxy.dashboard.activityLogSize` | 500 | Lines kept in the Activity view: agents and paths coming, going, and refused | | `proxy.dashboard.scrapeNowEnabled` | true | A Scrape button on each path, which scrapes it at once and shows the result | | `proxy.dashboard.maxSessions` | 50 | Open WebSocket sessions; more are closed | | `proxy.dashboard.allowedOrigins` | [] | Browser origins allowed besides the dashboard's host | | `proxy.dashboard.allowedHosts` | [] | Host names the dashboard answers to; empty turns the check off | | `proxy.dashboard.trustedProxies` | [] | Reverse proxies, IP addresses or CIDR ranges, whose `X-Forwarded-For` gives the client's address | | `proxy.dashboard.framingEnabled` | true | Lets any web page show the dashboard in a frame; false refuses framing | | `proxy.dashboard.links` | [] | Links from each path into other tools, each `{ name = "...", url = "...", icon = "..." }` | | `proxy.dashboard.screens` | [] | Screens `/screens` shows beside the dashboard, each `{ name = "...", url = "...", start = "..." }` | | `proxy.dashboard.agentScreens` | false | A tab on `/screens` for each connected agent that allows it, its relayed agent dashboard | | `proxy.dashboard.agentScreensMaxMBytes` | 96 | MiB the proxy keeps of every relayed agent dashboard's state together, as it estimates their memory | `password` turns on a login, from the dashboard's login page or, for a script, as HTTP Basic Auth, with `username` (`admin` unless set). Both are settable as `DASHBOARD_USERNAME` / `DASHBOARD_PASSWORD`, but have no command-line flags, since a command line shows in `ps`. The proxy never logs the password, and refuses to start with an empty username, a colon in it, or a control character in either. The dashboard serves plain HTTP, so put TLS in front of it; see [Login](https://prometheus-proxy.com/web-dashboard/index.md#login). Without a login, the proxy logs a warning at startup when the dashboard is enabled on all interfaces. A WebSocket from a browser origin other than the dashboard's host is refused; behind a reverse proxy that rewrites the Host header, list the public origin (for example `"https://dash.example.com"`) in `allowedOrigins`. An origin listed there pins its scheme for its host and port, so listing `"https://dash.example.com"` refuses `http://dash.example.com`. Being a list, `allowedOrigins` must be set in a config file rather than with `-D`. `allowedHosts` (for example `["dash.internal"]`) lists the names you reach the dashboard by, which stops DNS rebinding. It is off while empty, the default, and like `allowedOrigins` must be set in a config file. See [Exposure](https://prometheus-proxy.com/dashboard-exposure/index.md#exposure) for what both lists guard against. `trustedProxies` (for example `["10.0.0.5", "10.1.0.0/16"]`) lists the reverse proxies in front of the dashboard. A request from one of them takes the client's address from `X-Forwarded-For`, for the limit on wrong logins, the log, and the Activity view, so the users behind a reverse proxy don't share one limit. Each entry is an IP address or a CIDR range, and one that isn't fails startup. Empty, the default, every client is its connection's peer. It too must be set in a config file. See [Client Addresses](https://prometheus-proxy.com/dashboard-exposure/index.md#client-addresses). `framingEnabled` lets any web page show the dashboard in a frame, the default; `false` refuses framing on every response, but for the proxy's `/screens` while `screens` lists any or `agentScreens` is on, which may then frame it from the same origin. See [Exposure](https://prometheus-proxy.com/dashboard-exposure/index.md#exposure) for what framing lets another site's page do. `links` gives each row of the Paths table links into other tools, each a `name` and a `url` template whose placeholders (`{path}`, `{agent}`, `{identity}`, and `{label.}`) every row fills from its path, for example `{ name = "Grafana", url = "http://grafana:3000/d/proxy-targets?var-job={label.job}" }`. It too must be set in a config file, and a link the dashboard can't use stops the proxy at startup. On the screens page, a link into a tool `screens` lists opens in that tool's tab. See [Links](https://prometheus-proxy.com/web-dashboard/index.md#links). `screens` lists the screens the proxy's screens page, `/screens` on the dashboard's port, shows beside its dashboard, each in a tab: direct agent dashboards, Prometheus, Grafana, or any page that allows framing. Each has a `name`, the tab's title, whose lowercase form is its id in links into the page; a `url`, an absolute `http` or `https` URL, which a value from the environment can set with `${?NAME}`; and optionally a `start`, the path it opens on, appended to `url`, such as `/alerts`. While it lists any, the dashboard port's root leads to the page; with none, it leads to the dashboard, and `/screens` answers 404. It too must be set in a config file, and a list the page can't use stops the proxy at startup, naming the screen. See [Screens Page](https://prometheus-proxy.com/screens-page/index.md#screens). It runs on a separate port rather than the admin port, partly because the admin port is a servlet container that cannot host WebSockets, and partly so the dashboard can be firewalled without also cutting off the `/ping` and `/healthcheck` endpoints Kubernetes probes target. It serves plain HTTP, with **no TLS**, and without a `password` it has **no authentication**, like the admin and metrics endpoints, so treat the port as internal. See [Proxy Dashboard](https://prometheus-proxy.com/web-dashboard/index.md) for what it shows. ## Metrics Enable internal metrics collection: ```hocon proxy { metrics { enabled = true port = 8082 path = "metrics" } admin { enabled = true port = 8092 } } ``` | Setting / CLI Option / Env Var | Default | Description | |:-------------------------------------------------------------------------------------------------------------|:----------|:-------------------------------------------------| | [`proxy.metrics.enabled`](https://prometheus-proxy.com/cli-reference/index.md#proxy.metrics.enabled)
`--metrics, -e`
`METRICS_ENABLED` | false | Serve the proxy's metrics on a separate port | | [`proxy.metrics.port`](https://prometheus-proxy.com/cli-reference/index.md#proxy.metrics.port)
`--metrics_port, -m`
`METRICS_PORT` | 8082 | Their port | | `proxy.metrics.path` | "metrics" | Their path | The JVM's metric groups each have a switch under `proxy.metrics`, such as `proxy.metrics.standardExportsEnabled`, all off by default (see [JVM Metrics](https://prometheus-proxy.com/monitoring/index.md#jvm-metrics)). See [Monitoring](https://prometheus-proxy.com/monitoring/index.md) for the complete metrics reference. ## Internal Settings Configure agent cleanup and scrape request management. These settings have no command-line option or environment variable: set them in the config file, or with `-D`, as `-Dproxy.internal.maxAgentInactivitySecs=120`. ```hocon proxy.internal { staleAgentCheckEnabled = true maxAgentInactivitySecs = 60 // Evict after 60s of inactivity staleAgentCheckPauseSecs = 10 // Check every 10s scrapeRequestTimeoutSecs = 90 // Timeout for scrape requests } ``` | Setting | Default | Description | |:---------------------------------------------------|:--------|:--------------------------------------------------------------------------------------------------------| | `proxy.internal.staleAgentCheckEnabled` | true | Enable periodic stale agent cleanup | | `proxy.internal.maxAgentInactivitySecs` | 60 | Seconds an agent may go without contacting the proxy before the proxy evicts it | | `proxy.internal.staleAgentCheckPauseSecs` | 10 | Interval between cleanup checks | | `proxy.internal.scrapeRequestTimeoutSecs` | 90 | Timeout for individual scrape requests | | `proxy.internal.scrapeRequestBacklogUnhealthySize` | 25 | Backlog that marks the proxy unhealthy; each agent's queue is capped at twice this | | `proxy.internal.maxInFlightScrapeRequests` | 1000 | Max scrapes in flight across all agents; more get a 503 | | `proxy.internal.scrapeRequestMapUnhealthySize` | 0 | Scrapes in flight that mark the proxy unhealthy (0 = 80% of `proxy.internal.maxInFlightScrapeRequests`) | | `proxy.internal.chunkContextMapUnhealthySize` | 0 | Chunked transfers in progress that mark the proxy unhealthy (0 = 80% of the same) | | `proxy.internal.maxPathsPerAgent` | 20000 | Max paths one agent connection may register; more are refused (0 = unlimited) | | `proxy.internal.maxPathsPerIdentity` | 100000 | Max paths the agents of one auth identity may register together; more are refused (0 = unlimited) | | `proxy.internal.maxPathLength` | 512 | Max characters in a registered path (0 = unlimited) | | `proxy.internal.maxLabelsSizeBytes` | 8192 | Max size of a path's labels JSON, in bytes (0 = unlimited) | | `proxy.internal.maxLabelsPerPath` | 64 | Max labels in a path's labels JSON object (0 = unlimited) | | `proxy.internal.maxAgentFieldLength` | 256 | Max characters of an agent's name, host, launch ID, or endpoint (0 = unlimited) | | `proxy.internal.maxAgentProxyEndpoints` | 16 | Max entries of an agent's proxy endpoint list (0 = unlimited) | | `proxy.internal.maxTargetUrlLength` | 2048 | Max characters of a path's target URL, as the agent reports it (0 = unlimited) | | `proxy.internal.maxAgentsPerIdentity` | 10000 | Max agents connected as one identity with `transportFilterDisabled` (0 = unlimited) | | `proxy.internal.streamKeepAliveSecs` | 30 | Seconds a stream to or from an agent goes quiet before a keepalive, both ways (0 = off) | The five path limits are safety nets against a runaway or misbehaving agent, set well above normal use. A path over a limit is refused at registration, and the agent logs the rejection once without retrying it. A path too long, or with labels too large, is refused before it is checked against the agent's [identity patterns](#per-agent-identities); one with too many labels, or past a path count, after. The proxy warns when an agent reaches 80% of `maxPathsPerAgent`, and when an identity's agents reach 80% of `maxPathsPerIdentity`, and warns again only once the count has fallen below 70%, so a count that hovers at the threshold is warned of once. The counts and limits are on the proxy's `/metrics` too, in `proxy_identity_paths`, `proxy_agent_paths_max`, `proxy_identity_agents`, and `proxy_limit`: the Grafana dashboard's Paths & Limits row shows them, and the `ProxyIdentityNearPathLimit`, `ProxyAgentNearPathLimit`, and `ProxyIdentityNearAgentLimit` alerts warn past 80% (see [Proxy Metrics](https://prometheus-proxy.com/monitoring/index.md#proxy-metrics)). `maxPathsPerAgent` counts one connection's paths, and an agent may open any number of connections, so `maxPathsPerIdentity` counts the paths of every agent of an [identity](#per-agent-identities) together, whether or not the transport filter is on. With agent auth off, or every agent on the legacy `agentToken`, all agents share one identity, and the limit counts the paths of the whole fleet. An agent that takes over a path from another agent of its identity leaves the count as it was, so a redeploy at the limit still registers, but an agent that joins a consolidated path adds to it, and one that rejoins before the proxy has dropped its old connection counts twice until the proxy does. What the proxy keeps of a path is what these limits bound: a path with no labels costs at most about 3 KiB, with `maxPathLength` and `maxTargetUrlLength` at their defaults, and one with 64 labels filling `maxLabelsSizeBytes` about 20 KiB, or 28 KiB with non-Latin text. Lower `maxPathsPerIdentity` to keep one identity's paths within your heap. The agent limits bound what an agent reports about itself and its targets. The proxy only displays these values, in its logs, service discovery labels, dashboard, and `/debug` page, but it keeps them, and repeats some of them for every path the agent serves. A longer name, host name, launch ID, endpoint, or path source is cut to its first `maxAgentFieldLength` characters, a longer endpoint list to its first `maxAgentProxyEndpoints` entries, and a longer target URL to its first `maxTargetUrlLength` characters, after its credentials are redacted. The agent and its paths stay registered, and the proxy logs one warning naming what it cut. The agent redacts a target URL's query values before it sends it, so a real one is far shorter than 2048 characters. `maxAgentsPerIdentity` applies only with the [transport filter](#transport-filter) disabled; see there. ## Content Size Limits ```hocon proxy.internal { maxZippedContentSizeMBytes = 5 // Max zipped content size maxUnzippedContentSizeMBytes = 10 // Max unzipped content size } ``` `maxZippedContentSizeMBytes` bounds a result the agent sends in chunks, as it arrives, before the proxy unzips it: one past it fails its scrape with a 502 (`invalid_response`). `maxUnzippedContentSizeMBytes` bounds any result once it's unzipped, and one the agent sent without gzip, as it does a small one: one past it fails its scrape with a 413 (`payload_too_large`). The agent's `agent.http.maxContentLengthMBytes` bounds what it takes from a target ([Troubleshooting](https://prometheus-proxy.com/troubleshooting/index.md#413-payload-too-large)). ## Transport Filter The transport filter detects agent disconnections immediately. Disable it when using a reverse proxy like nginx, on the proxy and on each of its agents, since the proxy refuses an agent whose setting doesn't match the proxy's: ```hocon proxy.transportFilterDisabled = true // The proxy's config agent.transportFilterDisabled = true // Each agent's config ``` Each also takes [`--tf-disabled`](https://prometheus-proxy.com/cli-reference/index.md#proxy.transportFilterDisabled) or `TRANSPORT_FILTER_DISABLED=true`. !!! warning With `transportFilterDisabled`, the proxy can't see a connection close, only the agent's request stream end. An agent that disconnects ends that stream, and is removed at once. One that dies before opening its stream, or whose connection stays half-open, is removed after the inactivity timeout (default: 60 seconds, [`proxy.internal.maxAgentInactivitySecs`](#internal-settings)). !!! note "Give each agent its own identity" With the filter disabled, the proxy can't tie a call to a connection, so it binds each agent's calls to the auth identity the agent connected with. Agents that share an identity, including every agent on the legacy `proxy.agentToken`, can't be told apart, so give each agent its own `proxy.auth` token. See [Isolation Between Agents](https://prometheus-proxy.com/security/index.md#isolation-between-agents). !!! note "Agents per identity" With the filter disabled, every connect adds an agent on the proxy, so the proxy limits the agents connected as one auth identity to `proxy.internal.maxAgentsPerIdentity` (10,000). It refuses a connect past the limit with `RESOURCE_EXHAUSTED`, rather than drop an agent already connected, and the refused agent tries again after its reconnect pause. The proxy warns as an identity reaches 80% of the limit, again only once its count has fallen below 70%, and when it refuses a connect, at most once a minute for each identity. With agent auth off, or on the legacy `proxy.agentToken`, every agent has the same identity, so the limit is a total. Leave room for agents that count twice for a while: one that reconnects while its old connection is half-open, until the old one is evicted, and one whose registration is refused, once for each retry until each is evicted. Set `0` for no limit. ## gRPC Reflection [gRPC Reflection](https://grpc.io/docs/guides/reflection/) is disabled by default, because it lets anyone who reaches the agent port list and describe the proxy's API. Enable it for debugging and tooling: ```hocon proxy.reflectionDisabled = false ``` Or set `REFLECTION_DISABLED=false`. The [`--ref-disabled`](https://prometheus-proxy.com/cli-reference/index.md#proxy.reflectionDisabled) flag only turns it off. When agent authentication is configured (`proxy.agentToken` or `proxy.auth`), reflection calls need a valid agent token, like every other call on the agent port. ## Log Level ```hocon // Set log level in config file: proxy.logLevel = "debug" agent.logLevel = "debug" // Or via CLI: // java -jar prometheus-proxy.jar --log_level debug // java -jar prometheus-agent.jar --log_level debug // Or via environment variable: // PROXY_LOG_LEVEL=debug // AGENT_LOG_LEVEL=debug // Available levels: trace, debug, info, warn, error, off ``` ## Full Example [`examples/proxy.conf`](https://prometheus-proxy.com/examples/index.md#production-proxy-proxyconf) is a starting point for a proxy's config file: the settings the [Pre-Flight Checklist](https://prometheus-proxy.com/production/index.md#pre-flight-checklist) asks for, each with the section that explains it. The proxy also runs with no config file, on its defaults. ```hocon // A starting point for a production proxy: the settings Running in Production's Pre-Flight Checklist asks for, each // with the page that explains it. The proxy also runs with no config file, on the defaults this file starts from, // so keep only what you need; config/config.conf describes every setting. // https://prometheus-proxy.com/production/#pre-flight-checklist // // Secrets stay out of the file: the proxy reads the agent token from AGENT_TOKEN and the dashboard's password from // DASHBOARD_PASSWORD, which take precedence over a config file. proxy { // Where Prometheus scrapes, and where agents connect: the defaults. http.port = 8080 agent.port = 50051 // Who may connect as an agent. With no agent token, no identities, and no mutual TLS, any peer that reaches // agent.port can register paths. Set AGENT_TOKEN for one token every agent presents, or give each team an identity // of its own, limited to its paths, each token from the environment: // https://prometheus-proxy.com/security/#per-agent-identities-and-path-authorization // // auth = [ // { name = team-a, token = ${TEAM_A_TOKEN}, paths = ["team_a_*"] } // { name = team-b, token = ${TEAM_B_TOKEN}, paths = ["team_b_*"] } // ] // TLS on the agents' gRPC connections. With a trust collection, each agent must present a certificate too // (mutual TLS): https://prometheus-proxy.com/security/tls/ // // tls { // certChainFilePath = "/etc/prometheus-proxy/tls/server.crt" // privateKeyFilePath = "/etc/prometheus-proxy/tls/server.key" // trustCertCollectionFilePath = "/etc/prometheus-proxy/tls/ca.crt" // } // The proxy's metrics, on port 8082, for Prometheus to scrape, and its admin endpoints, on port 8092, for health // checks. Keep both ports off the public network: https://prometheus-proxy.com/monitoring/ metrics { enabled = true port = 8082 } admin { enabled = true port = 8092 } // The dashboard, which shows why a scrape fails without a restart. DASHBOARD_PASSWORD turns on its login, with the // username admin. It listens on this host only; to reach it from elsewhere, set host to an internal address, or // put a reverse proxy in front: https://prometheus-proxy.com/dashboard-exposure/ // // agentScreens adds each connected agent's dashboard to the screens page, http://:8094/, as a relayed agent // dashboard, through the agent's connection, so the agents open no port. Anyone who signs in sees every agent's, // and without DASHBOARD_PASSWORD the proxy warns of that at startup. An agent stays off with // agent.dashboard.showOnProxy = false: https://prometheus-proxy.com/screens-page/#agent-screens dashboard { enabled = true port = 8094 host = "127.0.0.1" agentScreens = true } // Prometheus service discovery: one scrape job finds every path the agents register. targetPrefix is the proxy's // scrape address as Prometheus reaches it: https://prometheus-proxy.com/service-discovery/ // // service.discovery { // enabled = true // targetPrefix = "proxy-host.example.com:8080" // } } ``` ## Full Reference See the complete configuration schema: [`config/config.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/config/config.conf) --- Source: https://prometheus-proxy.com/security/ # Security The proxy accepts connections from agents and scrapes from Prometheus, and out of the box it authenticates neither. This page covers what to decide before a proxy is reachable from more than one machine: who may connect as an agent, which paths each agent may register, who can reach the scrape port and the dashboard, and how credentials in target URLs and scrape headers are protected. Read it before you put a proxy into production, and before a second team shares one. ## Security Model The firewall stays closed: the agent opens its gRPC connection *outward* to the proxy, so no inbound port has to be opened to reach the agents' networks. From there: - An agent can be made to authenticate with a [pre-shared token](#agent-authentication-pre-shared-token), with [per-agent identities](#per-agent-identities-and-path-authorization) that also limit which paths it may register, with [mutual TLS](https://prometheus-proxy.com/security/tls/index.md), or with a token and mutual TLS together. - The proxy evicts an agent whose connection has gone quiet, so a dead connection doesn't hold its paths. - The proxy's scrape port, which Prometheus scrapes, has no authentication, so keep it where only Prometheus can reach it (see [Scrape Port Access](#scrape-port-access)). !!! warning "The agent gRPC port is unauthenticated by default" With neither a pre-shared agent token nor mutual TLS configured, any process that can reach the agent port (default `50051`) can register as an agent. Set a token (below), require mutual TLS, restrict the port to trusted networks, or do more than one of these. The proxy logs a startup warning when the agent port is left unauthenticated. ## TLS Encryption Agents connect to the proxy using [gRPC](https://grpc.io), which supports TLS with or without mutual authentication. | Mode | Proxy Needs | Agent Needs | |:----------------------|:----------------------------|:----------------------------| | **No TLS** | Nothing | Nothing | | **TLS (server only)** | Server cert + key | CA cert (trust store) | | **Mutual TLS** | Server cert + key + CA cert | Client cert + key + CA cert | See [TLS Setup](https://prometheus-proxy.com/security/tls/index.md) for detailed configuration instructions. ## Agent Authentication (Pre-Shared Token) By default the proxy accepts agent gRPC connections with **no application-level authentication**. Set a shared **pre-shared token** so the proxy rejects agents that do not present it: | Side | CLI | Env Var | Config | |:------|:----------------|:--------------|:-------------------| | Proxy | `--agent_token` | `AGENT_TOKEN` | `proxy.agentToken` | | Agent | `--agent_token` | `AGENT_TOKEN` | `agent.agentToken` | Both sides must use the **same** value. When set, the agent attaches the token as a gRPC metadata header on every call and the proxy rejects any call with a missing or mismatched token (`UNAUTHENTICATED`). When the token is empty (the default) and no [per-agent identities](#per-agent-identities-and-path-authorization) are configured, the port stays open, and the proxy logs a startup warning unless mutual TLS is configured, which already authenticates agents. The token is never logged. If a token or per-agent identities are configured without TLS, the proxy and the agent each log a startup warning that tokens are sent in cleartext. ```bash # Proxy requiring a token java -jar prometheus-proxy.jar --agent_token "$AGENT_TOKEN" # Agent presenting the token java -jar prometheus-agent.jar --config myconfig.conf --agent_token "$AGENT_TOKEN" ``` !!! note "Token vs. mutual TLS" A pre-shared token is a lightweight, app-level control that authenticates *that* a peer may connect. [Mutual TLS](https://prometheus-proxy.com/security/tls/index.md) also encrypts the channel and verifies a certificate's identity. The two can be combined. For production, prefer mutual TLS, restrict the agent port to trusted networks, or do both. ## Per-Agent Identities and Path Authorization A single shared `agentToken` authenticates agents but cannot tell them apart: any agent holding the token can register **any** path, including one already served by another agent, and so silently take over its metrics. Nothing fails and nothing alerts: the dashboard keeps drawing a line, but from another agent's numbers. The shared secret also makes revocation all-or-nothing, since rotating it means reconfiguring every agent at once, and leaves the proxy unable to say *who* registered a path. Define named identities under `proxy.auth`, each with a token and a list of allowed path glob patterns, to scope what each agent may register. This closes the takeover hole and makes a shared proxy safe for **multiple teams**, none of which can step on another's paths: ```hocon proxy { auth = [ { name = team-a, token = ${TEAM_A_TOKEN}, paths = ["team_a_*"] } { name = team-b, token = ${TEAM_B_TOKEN}, paths = ["team_b_*"] } { name = infra, token = ${INFRA_TOKEN}, paths = [] } // empty paths = may register any path ] } ``` Each token comes from an environment variable of the proxy's, through HOCON substitution, so no token is written in the config file; a variable that isn't set stops the proxy at startup. Each agent presents its identity's token the usual way (`--agent_token`, `AGENT_TOKEN`, or `agent.agentToken`), so the agent's config needs no other change. The proxy resolves the token to an identity and enforces, on every path registration, that the requested path matches one of the identity's patterns. | Condition | Result | |:-------------------------|:---------------------------------------------------| | Unknown token | Connection rejected with `UNAUTHENTICATED` | | Path matches a pattern | Registration succeeds | | Path matches no pattern | Registration fails with a "not authorized" reason | | Empty `paths` list | Identity may register **any** path (allow-all) | The [Basics Demo](https://prometheus-proxy.com/basics-demo/index.md#per-team-tokens-restrict-which-paths-an-agent-can-register) shows a contractor's agent refused a path its identity doesn't allow, with the proxy's reason, and in the [nginx Demo](https://prometheus-proxy.com/nginx-demo/index.md#two-agents-reach-the-proxy-through-nginx-over-tls) each agent has a separate token. Patterns are single-segment globs, such as `team_a_*`: `*` matches any run of characters and `?` matches exactly one. A pattern may start with one `/`, as a path may, and matches the same paths without it: `/team_a_*` is `team_a_*`. One with a `/` after that, such as `team_a/*` or `//team_a_*`, can't match any path the proxy accepts, so the proxy refuses to start with it, naming the identity and the pattern. A path is checked against the patterns only once its form and size have passed (`proxy.internal.maxPathLength` and `maxLabelsSizeBytes`; see [Proxy configuration](https://prometheus-proxy.com/configuration/proxy/index.md#internal-settings)), so a path that is too long, has more than one segment, or has whitespace, a control character, `?`, or `#` in it is refused as invalid, whatever the patterns. A `*` matches any run of characters, line breaks included, so this check is what keeps an agent from registering a path that would forge lines in the proxy's log. However many paths its patterns match, an identity's agents may hold at most `proxy.internal.maxPathsPerIdentity` (100,000) paths together, and each connection at most `maxPathsPerAgent` (20,000), so an identity can't register without limit by opening more connections. A path past either limit, or with more than `maxLabelsPerPath` (64) labels, is refused once the patterns have passed it. With agent auth off, or only the legacy `agentToken`, every agent shares one identity, and the limit counts them all; see [Internal Settings](https://prometheus-proxy.com/configuration/proxy/index.md#internal-settings). A path also belongs to the identity whose agent serves it: while a live agent serves a path in [consolidated mode](https://prometheus-proxy.com/advanced/index.md#consolidated-mode) (multiple agents serving one path), only an agent of the same identity may join it, so agents that share a consolidated path must present one identity. Another identity's registration is refused, and retried, until the path's agents are gone, even when its patterns match. A non-consolidated path is protected the same way. While a live agent serves it, only an agent of the same identity may take it over, which keeps redeploys working; an agent of another identity is refused with a reason, logged at WARN, until the serving agent is gone. With no agent authentication, or only the legacy shared token, every agent has the same identity, so takeovers behave as they always have. The legacy token and a `proxy.auth` identity cannot take over each other's live paths. !!! note "Config-file only" `proxy.auth` is a list of objects, so it can only be set in a config file: it has no CLI flag or environment variable, and the `-D` property override, parsed as Java properties, can't express a list. Identity names must be unique, tokens non-empty and distinct, from each other and from `proxy.agentToken`, and no identity may be named `legacy-agent-token`, the name the proxy gives the legacy shared token in its logs (the dashboard shows it as *shared token*), even when `proxy.agentToken` isn't set; the proxy fails fast at startup otherwise. A token can still come from the environment, through HOCON substitution, as in the example above. In Kubernetes, set the variables from a Secret, or keep the whole config in one (the proxy chart's `existingSecret`); a ConfigMap can be read by anyone who can read ConfigMaps in its namespace. Adding a team's identity restarts the shared proxy; [Onboarding a Team](https://prometheus-proxy.com/onboarding/index.md) walks through it, with a check before the restart and the way back if the proxy doesn't start. ### Migrating from a Shared Token Setting `proxy.auth` does **not** disable a legacy `proxy.agentToken`. When both are present, the shared token is honored as an additional **allow-all** identity (the proxy logs a warning that it is active), so you can adopt per-agent identities incrementally: 1. Add a `proxy.auth` entry per agent while leaving `proxy.agentToken` in place. Existing agents keep connecting with the shared token. 2. Move each agent onto a separate identity token, one at a time, stopping the old agent before starting its replacement. While the old agent still serves a path, the proxy rejects the new identity's registration of it; the new agent retries a rejected static path, first after `agent.internal.rejectedPathRetrySecs` and then on a backoff of up to `agent.internal.rejectedPathRetryMaxSecs`, and registers it once the old agent is gone. 3. Once every agent presents an identity token, remove `proxy.agentToken` to close the shared allow-all path. Step 3 is the one that actually secures anything: until the shared token is removed, anyone holding it still has allow-all access, since the per-agent entries constrain only the agents that use them. !!! note "Current limits" Identities are read only at startup, so adding or revoking one requires a **proxy restart**, which reconnects every agent (see [Onboarding a Team](https://prometheus-proxy.com/onboarding/index.md)). An identity comes from the token an agent presents, not from an mTLS client certificate, and tokens come from the proxy's config, written there or substituted from environment variables as described above. Weigh the work of managing tokens against [mutual TLS](https://prometheus-proxy.com/security/tls/index.md)'s when choosing how to authenticate agents; the two can be combined. ## Isolation between Agents Authenticated agents share one proxy, so the proxy keeps each agent to its own traffic: an agent's scrape results, heartbeats, and calls count only as its own, and behind a reverse proxy, one identity can connect only so many agents. ??? info "How the proxy keeps each agent to its own traffic" - **Scrape results come only from the agent the scrape was sent to.** Scrape IDs come from one counter shared by every agent, so the proxy checks each result, failure, and chunked-transfer message against the agent that owns the scrape. A message for another agent's scrape is dropped and logged at WARN, and the rest of the stream is still processed. - **Heartbeats are bound to their connection.** A heartbeat naming another agent is refused and does not keep that agent from being evicted as stale. - **Behind a reverse proxy, calls are bound to an identity.** With [`transportFilterDisabled`](https://prometheus-proxy.com/configuration/proxy/index.md#transport-filter) there is no connection to tie a call to, so the proxy records the auth identity an agent connected with and refuses a call naming that agent under a different identity. The stream an agent reads its scrape requests from checks, reads, and, when it ends, removes the one agent it found when it opened, so a stream that names an agent ID before that agent connects is refused, rather than later reading or removing the agent another identity connects with under that ID. - **Behind a reverse proxy, each identity's agents are limited.** Every connect adds an agent, so the proxy refuses a connect once `proxy.internal.maxAgentsPerIdentity` (10,000) agents are connected with the same identity, rather than let one caller add agents without limit. Agents of other identities are unaffected, but agents that share an identity share its limit, and with agent auth off that is every agent. !!! warning "Identity binding is only as fine-grained as the identities" Calls are bound only when agent authentication is configured (`proxy.auth` or `proxy.agentToken`). Agents that share one identity cannot be told apart when the transport filter is disabled, and that includes every agent on the legacy `proxy.agentToken`, which is a single allow-all identity. Behind a reverse proxy, give each agent its own `proxy.auth` token. With the transport filter enabled, calls are bound by connection and this limit does not apply. ## The Dashboard on a Shared Proxy Identities keep each team to its paths, but the proxy's [dashboard](https://prometheus-proxy.com/web-dashboard/index.md) has one login, which isn't scoped to a team. Whoever signs in sees every team's agents, with their identities, addresses, and host names; every path, with its target URL (its credentials masked) and its recent scrapes; what the proxy refused; and the proxy's settings. With [Scrape now](https://prometheus-proxy.com/web-dashboard/index.md#scrape-now) on, they can also scrape any path. With `proxy.dashboard.agentScreens` on (it's off by default), the same login opens each connected agent's [dashboard](https://prometheus-proxy.com/agent-dashboard/index.md) on the [screens page](https://prometheus-proxy.com/screens-page/index.md#agent-screens) as a relayed agent dashboard, through the agent's connection. It shows what the proxy's dashboard doesn't: every path the agent has, those the proxy refused included, with their target URLs; its proxy endpoints; its settings (never a token or password); its activity; and, while both the agent's and the proxy's `scrapeNowEnabled` are on, its Scrape now, which fetches a target from inside the agent's network whether or not the proxy has its path. A direct agent dashboard's password doesn't guard that page, and every agent shows there by default, embedded ones included, whether or not its direct dashboard is on. To keep it to the people who may read every team's agents: - **Set the dashboard's login**, with `DASHBOARD_PASSWORD` or `proxy.dashboard.password`, before turning `agentScreens` on. The proxy logs a warning at startup when it's on without one. - **Keep the port private.** Bind it to an address only operators reach with `proxy.dashboard.host`, and put TLS in front of it ([Exposing the Proxy Dashboard](https://prometheus-proxy.com/dashboard-exposure/index.md#exposure)). - **Leave `agentScreens` off** where more people can sign in than may read every agent. The **Settings** view shows whether it's on, as Agent screens. `proxy.dashboard.scrapeNowEnabled = false` turns off Scrape now, the proxy's and the agents' through it. - **Keep an agent off the proxy** with `agent.dashboard.showOnProxy = false`, in its config file, or as `-Dagent.dashboard.showOnProxy=false` on its command line, since it has no flag or environment variable. An embedded agent calls `setting("dashboard.showOnProxy", false)`, or sets the Ktor plugin's or the Spring Boot starter's `settings.dashboard.showOnProxy` to `false`. The agent's relayed dashboard is then off every proxy's screens page, and its paths and scrapes don't change. The agent's **Settings** view shows the choice as Show on proxy. ## Credentials in URLs A target URL can carry credentials, such as `http://user:pass@host/metrics?api_key=...`. The agent redacts the user info and query values everywhere a target URL is sent, logged, or displayed: in its logs, in what it sends the proxy, and so on the dashboard and `/debug` pages. It also redacts them inside HTTP client error messages, which embed the request URL. The proxy redacts target URLs from older agents as well. A config URL (`--config http://user:pass@host/agent.conf`) is redacted from the error the agent or proxy reports when the config fails to load, and when it loads but holds a setting that is rejected, such as a value of the wrong type or an unresolved `${…}` substitution, whose message names the URL the value came from. That covers the error log, which is all a standalone agent or proxy reports before it exits, and the `ConfigLoadException` an embedding application catches, every message in its cause chain included. The agent sends a URL's credentials as HTTP Basic auth with the first request to the target, and follows a redirect only within the target's origin, so they reach only that host. An `Authorization` header that Prometheus sends with the scrape takes precedence; the URL's credentials then answer only a 401 challenge. ## Scrape Port Access !!! warning "The scrape port is unauthenticated" The proxy's HTTP port (default `8080`) answers any client, with no authentication, and it listens on every interface by default (`proxy.http.host = "0.0.0.0"`). Anyone who can reach it can do what Prometheus does, and what Prometheus does reaches inside the agents' networks. A client of the scrape port can: - **Have the agents scrape their targets.** A `GET` of a registered path sends a scrape to the agent serving it, or to every agent serving it in [consolidated mode](https://prometheus-proxy.com/advanced/index.md#consolidated-mode). The agent fetches the path's `url` from inside its network and the proxy returns what the target answered. - **Choose the query string.** The request's query parameters are appended to the path's `url`, after any it already has. The agent doesn't filter them, so every parameter reaches the target. - **Choose the `Authorization` header.** The proxy forwards it to the agent, which sends it to the target ahead of any credentials in the path's `url` (see [Credentials in URLs](#credentials-in-urls)). - **List the paths.** With [service discovery](https://prometheus-proxy.com/service-discovery/index.md) enabled, its endpoint on this port lists every registered path, with the names and host names of the agents serving it. For most exporters that is a read of metrics Prometheus already collects. An exporter that takes its target as a query parameter is different: blackbox_exporter's and snmp_exporter's `/probe?target=…`, for example, turn the query string into a choice of host, so a client of the scrape port can have the exporter probe any address it can reach, from inside the agent's network, and read the result. Don't rely on the `target` in the path's `url` to prevent that, since which of two values for a repeated parameter an exporter uses is up to the exporter. To keep the port to Prometheus: - **Bind it to a private address** with `proxy.http.host`, one Prometheus can reach and the wider network can't (`-Dproxy.http.host=10.0.0.5` sets it from the command line). In a container, which listens on all of its interfaces, publish the port on a private address instead (`-p 10.0.0.5:8080:8080`). The proxy's Helm chart makes its Service a `ClusterIP`, and its `agentService` exposes only the gRPC port, so in Kubernetes the scrape port stays inside the cluster unless you expose it; a `NetworkPolicy` keeps it from the cluster's other pods as well. - **Firewall it** so that only Prometheus can connect. - **Take care with exporters that take a target parameter.** Serve them only through a proxy whose scrape port nothing but Prometheus can reach, and limit what the exporter can reach, with its settings or the network around it, to the hosts it should probe. ## Scrape Port Responses A compromised target can't serve a page that runs as script on the proxy's origin in an operator's browser, and a compromised agent can't send Prometheus a status line or a `Content-Type` header it would refuse. ??? info "What the scrape port passes through, and what it refuses" The proxy passes a target's `Content-Type` through only for the Prometheus exposition formats (`text/plain`, `application/openmetrics-text`, and the protobuf format), with only those formats' parameters (`version`, `charset`, `escaping`, `proto`, and `encoding`), each with a short value; anything else is served as `text/plain`. Every scrape-port response also carries `X-Content-Type-Options: nosniff` and `Content-Security-Policy: sandbox`. A status the proxy can't serve, one outside 200–599, or a 204, 205, or 304, which can't carry a body, fails the scrape with a 502 (`invalid_response`). ## Auth Header Forwarding When Prometheus scrape configurations include `basic_auth` or `bearer_token`, the proxy forwards the `Authorization` header to the agent over the gRPC channel. The agent then includes this header when fetching metrics from the target endpoint. ```yaml scrape_configs: # Bearer token authentication - job_name: 'app1' metrics_path: '/app1_metrics' bearer_token: 'eyJhbGciOiJIUzI1NiIs...' static_configs: - targets: ['proxy-host.example.com:8080'] # Basic auth - job_name: 'app2' metrics_path: '/app2_metrics' basic_auth: username: 'user' password: 's3cr3t' static_configs: - targets: ['proxy-host.example.com:8080'] # No auth - job_name: 'app3' metrics_path: '/app3_metrics' static_configs: - targets: ['proxy-host.example.com:8080'] ``` !!! danger "Credentials transmitted in plaintext without TLS" Without TLS, the `Authorization` header is transmitted in plaintext between the proxy and agent. The proxy logs a warning on the first request that includes an `Authorization` header when TLS is not enabled. **Always enable TLS when forwarding authentication headers.** ```text When Prometheus scrape configs include basic_auth or bearer_token, the proxy forwards the Authorization header to the agent over gRPC. Without TLS, credentials are transmitted in plaintext! Protect forwarded credentials with TLS: java -jar prometheus-proxy.jar \ --cert /path/to/server.crt \ --key /path/to/server.key java -jar prometheus-agent.jar \ --config myconfig.conf \ --trust /path/to/ca.crt ``` ## Redirects from Scrape Targets The agent follows a redirect only to the target's origin: the same scheme, host, and port. A redirect to any other origin is not followed: the scrape reports the 3xx status and the agent logs a warning. This keeps a target, or an open redirect reached through forwarded query parameters, from sending the agent to another host that would receive the target's basic-auth credentials, or to an internal address whose response would come back through the proxy. Point the path's `url` at the final location if a target redirects elsewhere. ## Scraping HTTPS Endpoints For HTTPS scrape targets signed by a custom or private CA, such as an internal corporate CA, point the agent at a trust store containing that CA so certificates are **still validated**: ```text Trust a custom or private CA for HTTPS scrape targets (validation stays enabled): Via CLI: java -jar prometheus-agent.jar \ --https_truststore /etc/agent/truststore.jks \ --https_truststore_password changeit \ --config myconfig.conf Via environment variables: HTTPS_TRUST_STORE_PATH=/etc/agent/truststore.jks HTTPS_TRUST_STORE_PASSWORD=changeit Via config file: agent.http.trustStorePath = "/etc/agent/truststore.jks" agent.http.trustStorePassword = "changeit" ``` An empty path uses the JDK default trust store. The trust store is process-wide: it applies to every HTTPS target the agent scrapes, and it is ignored when `trust_all_x509` is enabled. As a last resort, you can disable SSL verification entirely: ```text Disable SSL verification for HTTPS endpoints (development only!): Via CLI: java -jar prometheus-agent.jar --trust_all_x509 --config myconfig.conf Via environment variable: TRUST_ALL_X509_CERTIFICATES=true Via config file: agent.http.enableTrustAllX509Certificates = true ``` !!! warning "Development only" Only use `trust_all_x509` in development or testing environments: it disables certificate validation for **every** HTTPS target and takes precedence over the trust store. In production, configure a trust store, or give your metrics endpoints certificates the JDK already trusts, instead. ## Reporting a Vulnerability Report a security problem privately, not in a public issue, pull request, or discussion: use GitHub's [private vulnerability reporting](https://github.com/pambrose/prometheus-proxy/security/advisories/new). The report stays visible only to you and the maintainer until an advisory is published with the fix. Security fixes go into the latest release only, so upgrade to receive them. [`SECURITY.md`](https://github.com/pambrose/prometheus-proxy/blob/master/SECURITY.md) lists what a useful report includes, and which documented behavior is by design rather than a vulnerability: the agent port accepting any agent without a token, identities, or mutual TLS; the scrape port having no authentication, so that whoever can reach it can trigger scrapes with any query string and `Authorization` header; the admin and metrics ports having no authentication; and the dashboard having no TLS, and no authentication until its password is set. --- Source: https://prometheus-proxy.com/security/tls/ # TLS Setup ## Requirements ### TLS without Mutual Authentication Server-side TLS authenticates the proxy to the agent: | Component | Required Files | |:----------|:---------------------------------------------------------------------| | **Proxy** | `certChainFilePath` (server cert), `privateKeyFilePath` (server key) | | **Agent** | `trustCertCollectionFilePath` (CA cert) | ### TLS with Mutual Authentication Both sides authenticate each other: | Component | Required Files | |:----------|:-------------------------------------------------------------------------| | **Proxy** | `certChainFilePath`, `privateKeyFilePath`, `trustCertCollectionFilePath` | | **Agent** | `certChainFilePath`, `privateKeyFilePath`, `trustCertCollectionFilePath` | Each file can be given as its PEM text instead, in a setting or an environment variable; see [Certificates as Environment Variables](#certificates-as-environment-variables). The [Kubernetes Demo](https://prometheus-proxy.com/kubernetes-demo/index.md#mutual-tls-refuses-an-agent-without-a-certificate) runs mutual TLS between the Helm charts, and shows the proxy refusing an agent that has the token but no client certificate. !!! note "TLS provider" Since 4.1.0 the fat JARs and the Docker images use OpenSSL (BoringSSL) for TLS on Linux (x86_64, aarch_64), macOS (x86_64, aarch_64), and Windows (x86_64), and fall back to the JDK's TLS elsewhere. Certificates, keys, and the TLS options are used as before, but anything that differs between the two providers, such as the default cipher suites, now follows BoringSSL. ## Creating Certificates For a deployment, create a private CA and sign the proxy's certificate with it, and for mutual TLS each agent's too. With OpenSSL, or the LibreSSL that macOS ships: ```bash PROXY_HOST=proxy.example.com # the name agents use to reach the proxy # A private CA, which both sides trust openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:4096 -out ca.key openssl req -x509 -new -key ca.key -sha256 -days 3650 -subj "/CN=prometheus-proxy CA" \ -addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" -out ca.crt # The proxy's certificate, for PROXY_HOST openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out server.key openssl req -new -key server.key -subj "/CN=$PROXY_HOST" -out server.csr openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -sha256 -days 825 \ -extfile <(printf 'subjectAltName=DNS:%s\nextendedKeyUsage=serverAuth\n' "$PROXY_HOST") -out server.crt # An agent's certificate, for mutual TLS openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out client.key openssl req -new -key client.key -subj "/CN=agent-1" -out client.csr openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -sha256 -days 825 \ -extfile <(printf 'extendedKeyUsage=clientAuth\n') -out client.crt ``` The proxy takes `server.crt` and `server.key`, and for mutual TLS `ca.crt`; each agent takes `ca.crt`, and for mutual TLS `client.crt` and `client.key`, as in [Configuration](#configuration) below. Repeat the last three commands with another name for each further agent. `PROXY_HOST` must be the name agents dial, in `--proxy` or `agent.proxy.hostname`: the agent checks it against the certificate's subject alternative name. For an IP address, write `IP:%s` in place of `DNS:%s`. In an HA pair, sign every proxy's certificate with the same CA, since an agent uses one trust store for all its endpoints. `ca.key` signs every certificate, so keep it off the proxy and agent hosts. Each certificate stops working at its expiry, `-days` after it was signed, and the proxy and agents report when: `proxy_tls_cert_expiry_timestamp_seconds` and `agent_tls_cert_expiry_timestamp_seconds` give the first expiry in each collection they were given (see [Monitoring](https://prometheus-proxy.com/monitoring/index.md#proxy-metrics)), and the [alerting rules](https://prometheus-proxy.com/grafana/index.md#alerting-rules)' `ProxyTlsCertExpiringSoon` and `AgentTlsCertExpiringSoon` warn 14 days ahead. ## Configuration ### Without Mutual Authentication === "Config file" ```hocon proxy { agent.port = 50440 tls { certChainFilePath = "certs/server.pem" privateKeyFilePath = "certs/server.key" } } agent { proxy { hostname = "proxy-host.example.com" port = 50440 } tls { trustCertCollectionFilePath = "certs/ca.pem" } } ``` === "Command line" ```bash # Proxy with TLS (no mutual authentication): java -jar prometheus-proxy.jar \ --cert /path/to/server.crt \ --key /path/to/server.key ``` ```bash # Agent with TLS (no mutual authentication): java -jar prometheus-agent.jar \ --config myconfig.conf \ --trust /path/to/ca.crt ``` ### With Mutual Authentication === "Config file" ```hocon proxy { agent.port = 50440 tls { certChainFilePath = "certs/server.pem" privateKeyFilePath = "certs/server.key" trustCertCollectionFilePath = "certs/ca.pem" } } agent { proxy { hostname = "proxy-host.example.com" port = 50440 } tls { certChainFilePath = "certs/client.pem" privateKeyFilePath = "certs/client.key" trustCertCollectionFilePath = "certs/ca.pem" } } ``` === "Command line" ```bash # Proxy with mutual TLS: java -jar prometheus-proxy.jar \ --cert /path/to/server.crt \ --key /path/to/server.key \ --trust /path/to/ca.crt ``` ```bash # Agent with mutual TLS: java -jar prometheus-agent.jar \ --config myconfig.conf \ --cert /path/to/client.crt \ --key /path/to/client.key \ --trust /path/to/ca.crt ``` ## Confirm It's On The agent logs how it connected, each time it does: ```text Connected to proxy at proxy.example.com:50051 using TLS (no mutual auth) ``` With a client certificate, it says `using TLS with mutual auth`. `using plaintext` means it has no TLS settings, and it can't connect to a proxy that serves TLS. The [proxy's](https://prometheus-proxy.com/web-dashboard/index.md#the-settings-layout) and the [agent's](https://prometheus-proxy.com/agent-dashboard/index.md#the-settings-view) dashboards show the same in their Settings views' TLS row. From any host that can reach the proxy's agent port, OpenSSL shows the certificate the proxy serves, and whether it chains to your CA: ```bash openssl s_client -connect proxy.example.com:50051 -CAfile ca.crt /dev/null \ | grep -E 'subject=|Verify return code' ``` ```text subject=CN=proxy.example.com Verify return code: 0 (ok) ``` Any other return code means the agents won't trust it either: `21` (`unable to verify the first certificate`) is a certificate your CA didn't sign. LibreSSL, as macOS ships it, writes the subject as `subject=/CN=proxy.example.com`. ## Using the Included Test Certificates The repository includes test certificates for development: ```bash # Proxy with TLS (no mutual auth) using included certs java -jar prometheus-proxy.jar --config examples/tls-no-mutual-auth.conf # Agent with TLS (no mutual auth) using included certs java -jar prometheus-agent.jar --config examples/tls-no-mutual-auth.conf ``` For mutual auth: ```bash java -jar prometheus-proxy.jar --config examples/tls-with-mutual-auth.conf java -jar prometheus-agent.jar --config examples/tls-with-mutual-auth.conf ``` !!! warning "Test certificates only" The certificates in `testing/certs/` are for development and testing only. Generate your own certificates for production deployments. ## Certificates as Environment Variables Since 4.6.0, each certificate and key can be given as its PEM text rather than as a file. This suits a platform that passes secrets as environment variables, such as ECS, Cloud Run, Azure Container Apps, DigitalOcean, or Railway, and the Docker images, which have no shell to write a variable out to a file: | File setting | PEM setting | PEM environment variable | |:------------------------------|:-------------------------|:----------------------------| | `certChainFilePath` | `certChainPem` | `CERT_CHAIN_PEM` | | `privateKeyFilePath` | `privateKeyPem` | `PRIVATE_KEY_PEM` | | `trustCertCollectionFilePath` | `trustCertCollectionPem` | `TRUST_CERT_COLLECTION_PEM` | The settings sit under `proxy.tls` and `agent.tls`, beside the file settings, and the variables apply to whichever of the two reads them. A value can be: - the PEM text, line breaks and all, as `"$(cat server.key)"` gives it; - its base64, on one line, for a variable field that takes one line: `base64 < server.crt | tr -d '\n'`; - the PEM on one line, with each line break written as `\n`. Give each piece as a file or as PEM, not both: the proxy and the agent refuse a file and a PEM for the same piece. As with files, a certificate chain and a private key turn TLS on, and a trust collection alone turns it on for an agent. Only whether a PEM setting is set is logged, never its value, and there are no command-line options for them, so a key never shows in a process listing. An [embedded agent](https://prometheus-proxy.com/embedded-agent/index.md#configuring-in-code) takes them in code, with `trustCertificatePem` and `clientCertificatePem`. The [Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md#secrets-from-the-environment) runs this way: its proxy takes its certificate and key in `CERT_CHAIN_PEM` and `PRIVATE_KEY_PEM`, and its app's agent the certificate to trust in `PROMETHEUS_PROXY_CERT`, with no file mounted. The [nginx Demo](https://prometheus-proxy.com/nginx-demo/index.md#two-agents-reach-the-proxy-through-nginx-over-tls) ends the agents' TLS at nginx instead. ## TLS with Docker Mount certificate files into the container: ```bash # Proxy with TLS (no mutual auth): docker run --rm \ -p 127.0.0.1:8080:8080 \ -p 50440:50440 \ -p 127.0.0.1:8082:8082 \ -p 127.0.0.1:8092:8092 \ --mount type=bind,source="$(pwd)"/certs,target=/app/certs \ --mount type=bind,source="$(pwd)"/tls.conf,target=/app/tls.conf \ --env PROXY_CONFIG=tls.conf \ --env ADMIN_ENABLED=true \ --env METRICS_ENABLED=true \ pambrose/prometheus-proxy:4.9.0 # Agent with TLS (no mutual auth): docker run --rm \ -p 127.0.0.1:8083:8083 \ -p 127.0.0.1:8093:8093 \ --mount type=bind,source="$(pwd)"/certs,target=/app/certs \ --mount type=bind,source="$(pwd)"/tls.conf,target=/app/tls.conf \ --env AGENT_CONFIG=tls.conf \ --env PROXY_HOSTNAME=proxy-host:50440 \ pambrose/prometheus-agent:4.9.0 ``` Or give them as [environment variables](#certificates-as-environment-variables), with no file mounted: ```bash # Proxy with TLS, its certificate and key given as environment variables, no file mounted: docker run --rm \ -p 127.0.0.1:8080:8080 \ -p 50051:50051 \ --env CERT_CHAIN_PEM="$(base64 < server.crt | tr -d '\n')" \ --env PRIVATE_KEY_PEM="$(base64 < server.key | tr -d '\n')" \ pambrose/prometheus-proxy:4.9.0 # Agent trusting the CA that signed the proxy's certificate, given as an environment variable: docker run --rm \ --mount type=bind,source="$(pwd)"/agent.conf,target=/app/agent.conf \ --env AGENT_CONFIG=agent.conf \ --env PROXY_HOSTNAME=proxy-host:50051 \ --env TRUST_CERT_COLLECTION_PEM="$(cat ca.crt)" \ pambrose/prometheus-agent:4.9.0 ``` ## Override Authority When the proxy's certificate doesn't list the host name the agent dials among its subject alternative names, as with a test certificate, or one issued to a fixed name as on [Cloud Platforms](https://prometheus-proxy.com/cloud-platforms/index.md#securing-the-link), name the one it does list: ```hocon agent.tls.overrideAuthority = "expected.hostname.com" ``` Or via CLI: ```bash java -jar prometheus-agent.jar --override expected.hostname.com --config agent.conf ``` ## Example Config Files The repository includes complete TLS configuration examples: | File | Description | |:------------------------------------------------------------------------------------------------------------------------------------|:--------------------------| | [`examples/tls-no-mutual-auth.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/examples/tls-no-mutual-auth.conf) | Server-side TLS only | | [`examples/tls-with-mutual-auth.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/examples/tls-with-mutual-auth.conf) | Mutual TLS authentication | The [gRPC TLS documentation](https://github.com/grpc/grpc-java/tree/master/examples/example-tls) covers TLS for gRPC in more depth. --- Source: https://prometheus-proxy.com/service-discovery/ # Prometheus Service Discovery The proxy serves [Prometheus HTTP service discovery](https://prometheus.io/docs/prometheus/latest/http_sd/), so Prometheus finds each path as an agent registers it, with no change to its config. This is the proxy's side of discovery; on the agent's side, [Dynamic Target Discovery](https://prometheus-proxy.com/configuration/agent/index.md#dynamic-target-discovery) picks up the targets an agent scrapes from a file it watches. In the [Basics Demo](https://prometheus-proxy.com/basics-demo/index.md#what-this-demo-shows), Prometheus finds every service this way, and in the [Plain Kotlin Demo](https://prometheus-proxy.com/plain-kotlin-demo/index.md#scaling-out-and-in), it finds new workers' paths as the demo scales out. ## Enabling Service Discovery === "Config file" ```hocon proxy { service.discovery { enabled = true path = "discovery" targetPrefix = "proxy-host.example.com:8080" } } ``` === "Command line" ```bash # Enable service discovery via CLI: java -jar prometheus-proxy.jar \ --sd_enabled \ --sd_path discovery \ --sd_target_prefix proxy-host.example.com:8080 ``` === "Environment" ```text # Enable service discovery via environment variables: SD_ENABLED=true SD_PATH=discovery SD_TARGET_PREFIX=proxy-host.example.com:8080 ``` ## Discovery Endpoint Once enabled, the proxy exposes a JSON endpoint at the configured path (default: `/discovery`). Query it with: ```bash curl -s http://proxy-host.example.com:8080/discovery | jq '.' ``` ### Response Format The endpoint returns a JSON array in the format expected by Prometheus HTTP SD: ```json [ { "targets": ["proxy-host.example.com:8080"], "labels": { "__metrics_path__": "/app1_metrics", "agentName": "agent-01", "hostName": "internal.host.com", "env": "production", "team": "backend" } }, { "targets": ["proxy-host.example.com:8080"], "labels": { "__metrics_path__": "/app2_metrics", "agentName": "agent-01", "hostName": "internal.host.com", "env": "staging", "team": "backend" } } ] ``` Each entry contains: | Field | Description | |:--------------------------|:------------------------------------------------------------------| | `targets` | The proxy's address, `host:port`, from `targetPrefix` | | `labels.__metrics_path__` | The path to scrape on the proxy, after any path in `targetPrefix` | | `labels.__scheme__` | The scheme, when `targetPrefix` is a URL | | `labels.agentName` | Name(s) of agent(s) serving this path | | `labels.hostName` | Hostname(s) of agent(s) serving this path | | `labels.*` | Custom labels from agent `pathConfigs` | ## Prometheus Configuration Configure Prometheus to use HTTP service discovery: ```yaml scrape_configs: - job_name: 'prometheus-proxy-sd' http_sd_configs: - url: 'http://proxy-host.example.com:8080/discovery' refresh_interval: 30s ``` The `refresh_interval` controls how often Prometheus queries the discovery endpoint for changes. !!! tip "Dynamic target management" With service discovery enabled, you don't need to update `prometheus.yml` when agents register new paths. Prometheus automatically picks up new targets on the next refresh interval. ## Target Prefix The `targetPrefix` setting is the address Prometheus scrapes the advertised paths at: the external `host:port` of your proxy, as Prometheus reaches it. The default is `localhost:8080`. ```hocon proxy.service.discovery.targetPrefix = "proxy.example.com:8080" ``` It can also be an `http` or `https` URL, such as `https://proxy.example.com/prometheus/`. Prometheus doesn't accept a URL as a target, so the proxy splits it: the host and port become the target, the scheme becomes each target's `__scheme__` label, and any path goes in front of `__metrics_path__`. A value that is neither, or that has user info, a query, or a fragment, fails the proxy's startup when service discovery is enabled. ## Labels Labels configured in agent `pathConfigs` are included in the service discovery response. Prometheus can use these for relabeling, filtering, or target grouping: ```hocon agent.pathConfigs: [ { name: "Production API" path: prod_api_metrics labels: "{\"env\": \"production\", \"team\": \"backend\", \"service\": \"api\"}" url: "http://api.internal:9100/metrics" } ] ``` The labels appear in the discovery response and can be used in Prometheus relabeling rules. They must be a JSON object whose keys are label names that every Prometheus version accepts (`[a-zA-Z_][a-zA-Z0-9_]*`) and whose values are strings. Prometheus decodes the labels as a map of string to string, and one entry that isn't fails its whole discovery response, so the proxy leaves such entries out. The proxy logs a warning naming them when the path registers, and the agent logs one at startup for a `pathConfigs` entry. The path itself still registers. A path with more than `proxy.internal.maxLabelsPerPath` labels (64), or labels larger than `maxLabelsSizeBytes` (8 KiB), is refused instead (see [Internal Settings](https://prometheus-proxy.com/configuration/proxy/index.md#internal-settings)). A path can't be the discovery path (with service discovery on), `favicon.ico`, or the Blitz verification path (`proxy.internal.blitz.path`, with `proxy.internal.blitz.enabled` on: the file the Blitz service fetches to verify you own the site): the proxy serves those itself, so it refuses to register them. !!! note "Reserved label keys" The proxy computes `__metrics_path__`, `agentName`, and `hostName` itself, and it also drops every agent-supplied label whose key starts with `__`. In HTTP service discovery a target's labels override the scrape config's `__scheme__`, `__scrape_interval__`, `__scrape_timeout__`, and `__param_*`, so these would let an agent change how Prometheus scrapes it. The proxy logs a warning naming the dropped keys when the path registers. Agent labels can set `job` and `instance` by default. When agents run under separate [per-agent identities](https://prometheus-proxy.com/security/index.md#per-agent-identities-and-path-authorization), set `proxy.service.discovery.reserveJobAndInstanceLabels = true` so one team's agent can't label its targets as another team's job or instance. --- Source: https://prometheus-proxy.com/examples/ # Example Configs The repository ships a set of ready-to-run config files under [`examples/`](https://github.com/pambrose/prometheus-proxy/tree/master/examples). Each is shown below verbatim, except `examples/cloud-proxy`, which [Cloud Platforms](https://prometheus-proxy.com/cloud-platforms/index.md#where-to-run-the-proxy) shows. For the full set of options see [Agent Configuration](https://prometheus-proxy.com/configuration/agent/index.md) and [Proxy Configuration](https://prometheus-proxy.com/configuration/proxy/index.md). !!! note "Precedence" Config files rank below every other source but the built-in defaults: CLI args → env vars → `-D` properties → config file → built-in defaults. See the [CLI Reference](https://prometheus-proxy.com/cli-reference/index.md). ## Production Proxy — `examples/proxy.conf` { #production-proxy-proxyconf } A starting point for a proxy that carries production scrapes: the settings [Running in Production](production.md#pre-flight-checklist)'s Pre-Flight Checklist asks for. It turns on the proxy's metrics, its admin endpoints, and its dashboard, on `127.0.0.1`, with relayed agent dashboards on its screens page, and leaves agent identities, TLS, and Prometheus service discovery commented out, to fill in. The proxy reads the agent token from `AGENT_TOKEN` and the dashboard's password from `DASHBOARD_PASSWORD`, so neither secret goes in the file. The proxy also runs with no config file, on its defaults. ```hocon // A starting point for a production proxy: the settings Running in Production's Pre-Flight Checklist asks for, each // with the page that explains it. The proxy also runs with no config file, on the defaults this file starts from, // so keep only what you need; config/config.conf describes every setting. // https://prometheus-proxy.com/production/#pre-flight-checklist // // Secrets stay out of the file: the proxy reads the agent token from AGENT_TOKEN and the dashboard's password from // DASHBOARD_PASSWORD, which take precedence over a config file. proxy { // Where Prometheus scrapes, and where agents connect: the defaults. http.port = 8080 agent.port = 50051 // Who may connect as an agent. With no agent token, no identities, and no mutual TLS, any peer that reaches // agent.port can register paths. Set AGENT_TOKEN for one token every agent presents, or give each team an identity // of its own, limited to its paths, each token from the environment: // https://prometheus-proxy.com/security/#per-agent-identities-and-path-authorization // // auth = [ // { name = team-a, token = ${TEAM_A_TOKEN}, paths = ["team_a_*"] } // { name = team-b, token = ${TEAM_B_TOKEN}, paths = ["team_b_*"] } // ] // TLS on the agents' gRPC connections. With a trust collection, each agent must present a certificate too // (mutual TLS): https://prometheus-proxy.com/security/tls/ // // tls { // certChainFilePath = "/etc/prometheus-proxy/tls/server.crt" // privateKeyFilePath = "/etc/prometheus-proxy/tls/server.key" // trustCertCollectionFilePath = "/etc/prometheus-proxy/tls/ca.crt" // } // The proxy's metrics, on port 8082, for Prometheus to scrape, and its admin endpoints, on port 8092, for health // checks. Keep both ports off the public network: https://prometheus-proxy.com/monitoring/ metrics { enabled = true port = 8082 } admin { enabled = true port = 8092 } // The dashboard, which shows why a scrape fails without a restart. DASHBOARD_PASSWORD turns on its login, with the // username admin. It listens on this host only; to reach it from elsewhere, set host to an internal address, or // put a reverse proxy in front: https://prometheus-proxy.com/dashboard-exposure/ // // agentScreens adds each connected agent's dashboard to the screens page, http://:8094/, as a relayed agent // dashboard, through the agent's connection, so the agents open no port. Anyone who signs in sees every agent's, // and without DASHBOARD_PASSWORD the proxy warns of that at startup. An agent stays off with // agent.dashboard.showOnProxy = false: https://prometheus-proxy.com/screens-page/#agent-screens dashboard { enabled = true port = 8094 host = "127.0.0.1" agentScreens = true } // Prometheus service discovery: one scrape job finds every path the agents register. targetPrefix is the proxy's // scrape address as Prometheus reaches it: https://prometheus-proxy.com/service-discovery/ // // service.discovery { // enabled = true // targetPrefix = "proxy-host.example.com:8080" // } } ``` ## Production Agent — `examples/agent.conf` { #production-agent-agentconf } A starting point for an agent: the [Quick Start](https://prometheus-proxy.com/getting-started/index.md#create-an-agent-config)'s proxy and endpoint, which the Quick Start offers this file as a download for, and the agent's side of [Running in Production](production.md#pre-flight-checklist)'s Pre-Flight Checklist. It turns on the agent's admin endpoints, for health checks, serves its metrics through the proxy, and shows its dashboard on the proxy's screens page as a relayed agent dashboard. It leaves a name, a standby proxy, discovery, TLS, and a direct agent dashboard commented out, to fill in. The agent reads its token from `AGENT_TOKEN`, so no secret goes in the file. Set the proxy's host, `agent.proxy.hostname`, and the endpoint's `url` before you run it. ```hocon // A starting point for an agent: the Quick Start's two settings, the proxy and one endpoint, and the agent's side of // Running in Production's Pre-Flight Checklist, each with the page that explains it. Keep only what you need; // config/config.conf describes every setting. // https://prometheus-proxy.com/production/#pre-flight-checklist // // Secrets stay out of the file: the agent reads its token from AGENT_TOKEN, and a direct agent dashboard's password // from DASHBOARD_PASSWORD, which take precedence over a config file. agent { // How the agent appears in the proxy's dashboard, its logs, and its metrics; unset, the agent names itself after // its host: https://prometheus-proxy.com/configuration/agent/#agent-naming // // name = "my-agent" // The proxy this agent connects to, on port 50051 unless the address names another. With a standby proxy, list // both in endpoints instead, in failover order: https://prometheus-proxy.com/configuration/agent/#proxy-connection proxy.hostname = "proxy-host.example.com" // proxy.endpoints = ["proxy-host.example.com:50051", "standby-host.example.com:50051"] // Each entry serves one endpoint: Prometheus scrapes its path on the proxy, and the agent fetches its url. Its // labels, as JSON, are the labels Prometheus service discovery gives the path: // https://prometheus-proxy.com/configuration/agent/#path-configs pathConfigs: [ { name: "My App metrics" path: my_app_metrics url: "http://localhost:9100/metrics" // labels: """{"job": "my-app"}""" } ] // Paths from a file the agent watches, which it adds and removes without a restart: // https://prometheus-proxy.com/configuration/agent/#dynamic-target-discovery // // discovery { // enabled = true // file.path = "/etc/prometheus-agent/targets.conf" // } // TLS to the proxy: the CA that signed the proxy's certificate, and, for a proxy that requires mutual TLS, the // agent's certificate and key: https://prometheus-proxy.com/security/tls/ // // tls { // trustCertCollectionFilePath = "/etc/prometheus-agent/tls/ca.crt" // certChainFilePath = "/etc/prometheus-agent/tls/agent.crt" // privateKeyFilePath = "/etc/prometheus-agent/tls/agent.key" // } // Admin endpoints on port 8093, for health checks: /ping for liveness, and /healthcheck for readiness. // https://prometheus-proxy.com/monitoring/#admin-endpoints admin { enabled = true port = 8093 } // The agent's metrics, which the proxy serves at /agent_metrics, read in-process, with no port to open: // https://prometheus-proxy.com/monitoring/ metrics.proxyPath = agent_metrics // The agent's dashboard. A proxy with agentScreens on shows it as a relayed agent dashboard, through the agent's // connection, unless showOnProxy is false. A direct agent dashboard serves it on port 8095 of this host too, with // its login from DASHBOARD_PASSWORD: // https://prometheus-proxy.com/agent-dashboard/#direct-and-relayed-agent-dashboards dashboard { showOnProxy = true // enabled = true // port = 8095 // host = "127.0.0.1" } } ``` ## Self-Monitoring — `simple.conf` Turns on admin on both components and the proxy's metrics port, points the agent at the proxy's `/metrics` endpoint, and has the agent serve its own metrics at `/agent_metrics`, in-process, with no port (`agent.metrics.proxyPath`), so the proxy and agent monitor themselves. A good first run on a single host. ```hocon // The proxy and the agent monitor themselves: the agent serves the proxy's // and its own metrics through the proxy, at /proxy_metrics and // /agent_metrics. // // On one host, run both with --config examples/simple.conf. In Docker, an // agent's localhost is its own container, so the Docker quick start puts // the two containers on one network and gives the agent PROXY_HOSTNAME, // the proxy container's name: the agent connects to the proxy there, and // fetches the proxy's metrics from there too. // // The proxy's dashboard is on, at http://localhost:8094/, which opens its // screens page: the proxy's dashboard, and the agent's as a relayed agent // dashboard, through the agent's connection. It has no password, so it // listens on this host only, and the proxy warns at startup that anyone // who reaches the port can read the agent's dashboard. // The proxy's host for its metrics: PROXY_HOSTNAME when it's set, so a host // name without a port, and localhost otherwise. The agent serves its own // metrics in-process, with no port (metrics.proxyPath). proxyMetricsHost = localhost proxyMetricsHost = ${?PROXY_HOSTNAME} proxy { admin { debugEnabled = false enabled = true } metrics.enabled: true dashboard { enabled = true port = 8094 host = "127.0.0.1" agentScreens = true } http.requestLoggingEnabled: true } agent { proxy.hostname = localhost admin.enabled: true // The agent's own metrics, served at this path through the proxy. metrics.proxyPath = agent_metrics metrics.proxyPathLabels = "{\"key3\": \"value3\", \"key4\": \"4\"}" pathConfigs: [ { name: "Proxy metrics" path: proxy_metrics labels: "{\"key1\": \"value1\", \"key2\": \"2\"}" url: "http://"${proxyMetricsHost}":8082/metrics" } ] } ``` Run it with: ```bash java -jar prometheus-proxy.jar --config examples/simple.conf java -jar prometheus-agent.jar --config examples/simple.conf ``` Then open , the proxy's [screens page](https://prometheus-proxy.com/screens-page/index.md), which shows the proxy's [dashboard](https://prometheus-proxy.com/web-dashboard/index.md) and the agent's as a [relayed agent dashboard](https://prometheus-proxy.com/screens-page/index.md#agent-screens). The dashboard has no password, so it listens on `127.0.0.1` only, and the proxy warns at startup that anyone who reaches its port can read the agent's dashboard: expected here. Before you share a dashboard, see [Exposing the Proxy Dashboard](https://prometheus-proxy.com/dashboard-exposure/index.md). In Docker, the agent's `localhost` is its container, so give it `PROXY_HOSTNAME`, the proxy's host name without a port: the agent connects to the proxy there, and fetches the proxy's metrics from there too. The [Docker quick start](https://prometheus-proxy.com/docker/index.md#basic-usage) runs it that way. ## Debugging a Local Run — `prom-agent.conf` The same self-monitoring setup as `simple.conf`, dashboard included, turned up for troubleshooting: the proxy's debug servlet is enabled on the admin port, the `labels` are dropped so the output stays readable, and the agent's metrics port stays on beside its `/agent_metrics` path, so you can `curl localhost:8083/metrics` directly. Two toggles are left commented out for when you need them — `transportFilterDisabled` for running behind an nginx reverse proxy, and `scrapeTimeoutSecs` for endpoints slower than the 15-second default. ```hocon // The proxy's host for its metrics, as in simple.conf: PROXY_HOSTNAME when // it's set, as when the agent runs in its own container, so a host name // without a port, and localhost otherwise. proxyMetricsHost = localhost proxyMetricsHost = ${?PROXY_HOSTNAME} proxy { admin.debugEnabled = true admin.enabled: true metrics.enabled: true // The dashboard and its screens page, with the agent's relayed agent // dashboard, as in simple.conf: http://localhost:8094/, on this host only. dashboard { enabled = true port = 8094 host = "127.0.0.1" agentScreens = true } //transportFilterDisabled = true http.requestLoggingEnabled: true } agent { //scrapeTimeoutSecs = 16 proxy.hostname = localhost admin.enabled: true // The agent's own metrics, served at this path through the proxy, in-process. metrics.proxyPath = agent_metrics // The metrics port stays on too, so you can curl localhost:8083/metrics directly while debugging. metrics.enabled: true //transportFilterDisabled = true pathConfigs: [ { name: "Proxy metrics" path: proxy_metrics url: "http://"${proxyMetricsHost}":8082/metrics" } ] } ``` This is the config behind the bundled *Agent (no auth)* IntelliJ run configuration in `.run/`. ## Multiple Application Endpoints — `myapps.conf` Three application endpoints, each on a separate proxy path and tagged with custom `labels`. This is the typical shape of a real agent config. ```hocon agent { pathConfigs: [ { name: "App1 metrics" path: app1_metrics labels: "{\"key1\": \"value1\", \"key2\": \"2\"}" url: "http://app1.local:9100/metrics" }, { name: "App2 metrics" path: app2_metrics labels: "{\"key3\": \"value3\", \"key4\": \"4\"}" url: "http://app2.local:9100/metrics" }, { name: "App3 metrics" path: app3_metrics labels: "{\"key5\": \"value5\", \"key6\": \"6\"}" url: "http://app3.local:9100/metrics" } ] } ``` Prometheus then scrapes `/app1_metrics`, `/app2_metrics`, and `/app3_metrics` from the proxy. See [Multiple Endpoints](https://prometheus-proxy.com/configuration/agent/index.md#multiple-endpoints) on the Agent Configuration page. ## Metric Filtering — `agent-filters.conf` Drops whole metric families at the agent, before the payload is gzipped, chunked, and sent across the WAN. Filters live in a top-level `agent.filters` list keyed by `path` rather than nested inside `pathConfigs`, so a filter applies to that path whether it was registered statically or by dynamic discovery. ```hocon agent { pathConfigs: [ { name: "app1" path: "app1_metrics" url: "http://app1:9090/metrics" } ] // Drop Go runtime GC metrics for app1 before they cross the WAN. // Regexes are fully anchored, matching Prometheus relabel_config semantics: // "go_" matches nothing; "go_.*" matches go_gc_duration_seconds. filters: [ { path: "app1_metrics" metricNameAllow: [] metricNameDeny: [ "go_gc_.*", "go_memstats_.*" ] } ] } ``` Regexes are fully anchored, matching Prometheus `relabel_config` semantics: `go_` matches nothing, while `go_.*` matches `go_gc_duration_seconds`. See [Metric Filtering](https://prometheus-proxy.com/configuration/agent/index.md#metric-filtering). ## Dynamic Discovery Targets — `discovery-targets.conf` Unlike every other file on this page, this one is **not** passed to `--config`. It is the targets file an agent watches when [dynamic target discovery](https://prometheus-proxy.com/configuration/agent/index.md#dynamic-target-discovery) is enabled, so it has a top-level `paths` list and no `agent { }` wrapper. The agent re-reads it every `reconcileIntervalSecs` and registers, unregisters, or re-registers paths to match — no restart, and paths that did not change keep scraping. ```hocon // Dynamic target discovery file, referenced by agent.discovery.file.path. // // This is a standalone targets file, NOT an agent config -- there is no `agent { }` wrapper here. // Point an agent at it from that agent's own config: // // agent { // discovery { // enabled = true // file.path = "examples/discovery-targets.conf" // reconcileIntervalSecs = 30 // } // } // // The agent re-reads this file every reconcileIntervalSecs and registers, unregisters, or // re-registers paths so the live set matches it -- no restart, and paths that did not change keep // scraping. Static agent.pathConfigs entries are a baseline reconciliation never touches; if a path // here collides with a static one, the static entry wins and the collision is logged. // // JSON is equally valid, since HOCON is a JSON superset -- convenient if this file is generated. paths = [ // Only `path` and `url` are required: `name` defaults to `path`, `labels` defaults to "{}". An entry whose // `path` or `url` is blank is skipped when this file is read, reported once, and the rest of the file applies. { path = "app1_metrics", url = "http://app1.local:9100/metrics" } // Full form. `labels` is a JSON *string*, not a nested object; HOCON triple quotes avoid the // backslash escaping used in the pathConfigs examples. { name = "App2 metrics" path = "app2_metrics" url = "http://app2.local:9100/metrics" labels = """{"env": "prod", "team": "platform"}""" } ] // `path` must be a single segment: the proxy serves each registered path at /, so an entry // with a multi-segment value like "app/metrics", or a second leading slash, as "//app_metrics" // has, is skipped when the file is read. Use "app_metrics". // Substitutions are resolved, so a generated or environment-driven file can avoid repetition. // The ${?VAR} form is optional: it overrides the preceding value when set and falls back to it // when unset. Uncomment to try: // // host = "app3.local" // port = 9100 // port = ${?METRICS_PORT} // // paths = [ // { path = "app3_metrics", url = "http://"${host}":"${port}"/metrics" } // ] // Removing every discovered path is spelled `paths = []` -- an empty-but-valid file is a real // instruction and is honored. Deleting or corrupting this file is NOT: an unreadable file is // treated as a failed read, so the agent logs a warning, skips the tick, and keeps its // last-known-good set rather than tearing every target down on a bad write, re-registering it if // the agent reconnects to the proxy meanwhile. ``` An agent points at it from its config: ```hocon agent { discovery { enabled = true file.path = "examples/discovery-targets.conf" reconcileIntervalSecs = 30 } } ``` ## Prometheus Federation — `federate.conf` Pulls metrics from an existing Prometheus server through its `/federate` endpoint, exposing them on a proxy path, and serves the agent's own metrics at `/agent_metrics`, in-process, with no port. See [Prometheus Federation](https://prometheus-proxy.com/advanced/index.md#prometheus-federation). ```hocon agent { // The agent's own metrics, served at this path through the proxy, in-process, with no port. metrics.proxyPath = agent_metrics pathConfigs: [ { name: "Federate metrics" path: federate_metrics url: "http://prometheus:9090/federate?match[]={job=~'.*'}" } ] } ``` ## Server-Only TLS — `tls-no-mutual-auth.conf` Encrypts the gRPC channel with a server certificate; the agent verifies the proxy but does not present a client certificate. Note the non-default agent port `50440` and the `overrideAuthority` used to match the test fixture's SAN. ```hocon // TLS without mutual authentication: the agent verifies the proxy's certificate, but the proxy does not // verify agents. If the agent port is reachable by untrusted peers, also configure agent tokens. // // The certificates and keys under testing/certs are TEST FIXTURES committed to a public repository, so their // private keys are not secret. Never use them outside local testing; generate your own for any real deployment. proxy { agent.port = 50440 tls { certChainFilePath = "testing/certs/server1.pem" // Server certificate chain file path privateKeyFilePath = "testing/certs/server1.key" // Server private key file path trustCertCollectionFilePath = "" // Trust certificate collection file path } } agent { proxy { hostname = "localhost" // Proxy hostname port = 50440 // Proxy port } // Only trustCertCollectionFilePath is required on the client with TLS (no mutual authentication) tls { overrideAuthority = "foo.test.google.fr" // Override authority (for testing only) certChainFilePath = "" // Client certificate chain file path privateKeyFilePath = "" // Client private key file path trustCertCollectionFilePath = "testing/certs/ca.pem" // Trust certificate collection file path } } ``` ## Mutual TLS — `tls-with-mutual-auth.conf` Both sides present certificates: the proxy trusts the client CA and the agent supplies its `certChainFilePath` / `privateKeyFilePath`. This is the recommended production posture. ```hocon // TLS with mutual authentication: the agent verifies the proxy's certificate, and the proxy requires a client // certificate from each agent. // // The certificates and keys under testing/certs are TEST FIXTURES committed to a public repository, so their // private keys are not secret. Never use them outside local testing; generate your own for any real deployment. proxy { agent.port = 50440 tls { certChainFilePath = "testing/certs/server1.pem" // Server certificate chain file path privateKeyFilePath = "testing/certs/server1.key" // Server private key file path trustCertCollectionFilePath = "testing/certs/ca.pem" // Trust certificate collection file path } } agent { proxy { hostname = "localhost" // Proxy hostname port = 50440 // Proxy port } // With mutual authentication the client also presents its own certificate chain and private key tls { overrideAuthority = "foo.test.google.fr" // Override authority (for testing only) certChainFilePath = "testing/certs/client.pem" // Client certificate chain file path privateKeyFilePath = "testing/certs/client.key" // Client private key file path trustCertCollectionFilePath = "testing/certs/ca.pem" // Trust certificate collection file path } } ``` See [TLS Setup](https://prometheus-proxy.com/security/tls/index.md) for [creating certificates](https://prometheus-proxy.com/security/tls/index.md#creating-certificates) and the full TLS option set. --- Source: https://prometheus-proxy.com/deploy/ # Deploy Once the Quick Start works, these pages run the proxy and its agents for real. Pick the page for where they'll run, and read Running in Production before they carry production scrapes, whichever you pick.
- [Docker](https://prometheus-proxy.com/docker/index.md) The multi-platform images on Docker Hub, run on their own or with Docker Compose, from a first run to a production setup with TLS and a token. - [Kubernetes](https://prometheus-proxy.com/kubernetes/index.md) The Helm charts: the proxy beside Prometheus, an agent inside each target cluster, and how Prometheus finds the paths, with TLS, health probes, and resources. - [Cloud Platforms](https://prometheus-proxy.com/cloud-platforms/index.md) An app on ECS, Cloud Run, or Azure Container Apps, scraped through an embedded agent, with the proxy on AWS, GCP, Azure, DigitalOcean, or Railway. - [Running in Production](https://prometheus-proxy.com/production/index.md) A pre-flight checklist, then security, running as a service, high availability, sizing, logging, and shutdown, section by section. - [Advanced Topics](https://prometheus-proxy.com/advanced/index.md) nginx in front of the proxy, Prometheus federation, consolidated mode, gRPC reflection and keepalive tuning, performance tuning, stale agent cleanup, and Zipkin tracing.
--- Source: https://prometheus-proxy.com/docker/ # Docker Multi-platform images (amd64, arm64, s390x, ppc64le) are published on Docker Hub for every release. ```bash docker pull pambrose/prometheus-proxy:4.9.0 docker pull pambrose/prometheus-agent:4.9.0 ``` ## Basic Usage In a container, `localhost` is the container itself, so these put the proxy and the agent on a network they share, and the agent reaches the proxy by its container name, given in `PROXY_HOSTNAME`. The agent connects over that network, so the proxy doesn't publish the agents' port, 50051, and publishes its scrape port on the host's `127.0.0.1` only, for `curl` on the same host. In a real deployment the agent runs on another host, inside the firewall, with `PROXY_HOSTNAME` set to the proxy's address and no shared network, and the proxy publishes 50051 and requires TLS and a token, as in [Production Setup](#production-setup). ### Proxy ```bash # Create a network for the proxy and agent containers: docker network create prometheus-proxy-net # Start a proxy container on it, with its metrics enabled. The agent reaches the proxy over the network, so only the # scrape port is published, on this host's loopback: docker run --rm --name prometheus-proxy --network prometheus-proxy-net \ -p 127.0.0.1:8080:8080 \ --env METRICS_ENABLED=true \ pambrose/prometheus-proxy:4.9.0 ``` ### Agent with Remote Config Run the agent in another terminal. Its config, [`simple.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/examples/simple.conf), serves the proxy's and the agent's own metrics through the proxy, and fetches the proxy's from the `PROXY_HOSTNAME` host, which is why the proxy needs `METRICS_ENABLED`: ```bash # Start an agent with a remote config, connecting to the proxy by its container name: docker run --rm --network prometheus-proxy-net \ --env PROXY_HOSTNAME=prometheus-proxy \ --env AGENT_CONFIG='https://raw.githubusercontent.com/pambrose/prometheus-proxy/4.9.0/examples/simple.conf' \ pambrose/prometheus-agent:4.9.0 # Scrape the proxy's and the agent's own metrics through the proxy: curl http://localhost:8080/proxy_metrics curl http://localhost:8080/agent_metrics ``` ## Running in the Background The examples above run in the foreground: the container stays attached to your terminal and logs there until you stop it with Ctrl+C, and `--rm` then removes it. To keep a container running in the background, start it with `--detach` and give it a `--name` to manage it by. `--restart unless-stopped` also starts it again if it exits or Docker restarts, until you stop it. Docker doesn't allow `--rm` with `--restart`, so leave `--rm` out. These run on the network from [Basic Usage](#basic-usage): ```bash # Run the proxy in the background: docker run --detach --name prometheus-proxy --restart unless-stopped --network prometheus-proxy-net \ -p 127.0.0.1:8080:8080 \ pambrose/prometheus-proxy:4.9.0 # Run an agent in the background with a local config file: docker run --detach --name prometheus-agent --restart unless-stopped --network prometheus-proxy-net \ --mount type=bind,source="$(pwd)"/agent.conf,target=/app/agent.conf \ --env AGENT_CONFIG=agent.conf \ --env PROXY_HOSTNAME=prometheus-proxy \ pambrose/prometheus-agent:4.9.0 ``` Manage a background container by its name: ```bash docker ps --filter name=prometheus- # check that they are running docker logs --follow prometheus-proxy # follow a container's log docker restart prometheus-agent # restart it, e.g. to pick up an edited agent.conf docker stop prometheus-agent # stop it; it stays stopped when Docker restarts docker rm prometheus-agent # remove the stopped container ``` To move a container to a new release, stop and remove it, then run it again with the new version's tag. ## Production Setup These run in the background under a restart policy, as described in [Running in the Background](#running-in-the-background), with the agent on another host. The proxy publishes the agents' port, 50051, on every interface, so the agent connects over TLS and presents a token. Make the proxy's certificate and key (`server.crt`, `server.key`) and the token (`agent-token`) as [Securing the Link](https://prometheus-proxy.com/cloud-platforms/index.md#securing-the-link) does, and copy `server.crt` and `agent-token`, never the key, to the agent's host. The certificate is issued to the name `prometheus-proxy`, which the agent checks it against (`OVERRIDE_AUTHORITY`). The proxy publishes its scrape, metrics, and admin ports on its host's `127.0.0.1` only, as they have no authentication. For a Prometheus on another host, publish the scrape port on a private address it can reach instead (`-p 10.0.0.5:8080:8080`), and firewall it; see [Scrape Port Access](https://prometheus-proxy.com/security/index.md#scrape-port-access). ### Proxy with Admin and Metrics ```bash # Production proxy with admin and metrics enabled, in the background. Agents on other hosts connect to 50051, published # on every interface, over TLS and with the token; the other ports are published on this host's loopback only: docker run --detach --name prometheus-proxy \ -p 50051:50051 \ -p 127.0.0.1:8080:8080 \ -p 127.0.0.1:8082:8082 \ -p 127.0.0.1:8092:8092 \ --env CERT_CHAIN_PEM="$(base64 < server.crt | tr -d '\n')" \ --env PRIVATE_KEY_PEM="$(base64 < server.key | tr -d '\n')" \ --env AGENT_TOKEN="$(cat agent-token)" \ --env ADMIN_ENABLED=true \ --env METRICS_ENABLED=true \ --restart unless-stopped \ pambrose/prometheus-proxy:4.9.0 ``` ### Agent with Local Config File ```bash # Agent with a local config file (bind mount), in the background, on another host. It trusts the proxy's # certificate, checks it against the name it was issued to, and presents the token: docker run --detach --name prometheus-agent \ -p 127.0.0.1:8083:8083 \ -p 127.0.0.1:8093:8093 \ --mount type=bind,source="$(pwd)"/prom-agent.conf,target=/app/prom-agent.conf \ --env AGENT_CONFIG=prom-agent.conf \ --env PROXY_HOSTNAME=proxy-host.example.com \ --env TRUST_CERT_COLLECTION_PEM="$(cat server.crt)" \ --env OVERRIDE_AUTHORITY=prometheus-proxy \ --env AGENT_TOKEN="$(cat agent-token)" \ --env ADMIN_ENABLED=true \ --env METRICS_ENABLED=true \ --restart unless-stopped \ pambrose/prometheus-agent:4.9.0 ``` !!! info "Container WORKDIR and user" The `WORKDIR` of both proxy and agent images is `/app`. Use `/app` as the base directory in `--mount` target paths. Both images run as a non-root user with UID and GID 1001, given by number, so a mounted config or certificate must be readable by that user. In Kubernetes, `runAsNonRoot` can check the user without a `runAsUser`. ## Docker Compose ```yaml services: proxy: image: pambrose/prometheus-proxy:4.9.0 # Published on this host's loopback only. The agent reaches the gRPC port, 50051, over the compose network, so # it isn't published at all. ports: - "127.0.0.1:8080:8080" # HTTP scrape port - "127.0.0.1:8082:8082" # Metrics port - "127.0.0.1:8092:8092" # Admin port environment: - ADMIN_ENABLED=true - METRICS_ENABLED=true - SD_ENABLED=true - SD_TARGET_PREFIX=proxy:8080 restart: unless-stopped agent: image: pambrose/prometheus-agent:4.9.0 ports: - "127.0.0.1:8083:8083" # Metrics port - "127.0.0.1:8093:8093" # Admin port environment: - PROXY_HOSTNAME=proxy - ADMIN_ENABLED=true - METRICS_ENABLED=true - AGENT_CONFIG=agent.conf volumes: - ./agent.conf:/app/agent.conf:ro depends_on: - proxy restart: unless-stopped ``` The agent reaches the proxy over the compose network, so the agents' gRPC port, 50051, isn't published, and the other ports are published on the host's `127.0.0.1` only: nothing in this stack asks for a token or a login, and a port Docker publishes on every interface gets past the host's firewall, such as ufw or firewalld. For agents on other hosts, the proxy publishes 50051 and requires a token and TLS, as the compose file in [Where to Run the Proxy](https://prometheus-proxy.com/cloud-platforms/index.md#where-to-run-the-proxy) does. For a stack you can start as-is, [`etc/compose/proxy.yml`](https://github.com/pambrose/prometheus-proxy/blob/master/etc/compose/proxy.yml) runs a proxy, an agent, and a Prometheus server that scrapes the proxy's and agent's own metrics through the proxy, with its ports published the same way. The agent serves its own at `/agent_metrics`, in-process (`agent.metrics.proxyPath`), so its metrics port stays off. From a checkout of the repository: ```bash docker compose -f etc/compose/proxy.yml up ``` Prometheus is then at `http://localhost:9090`, with both targets up on its **Targets** page. That runs the stack in the foreground until Ctrl+C. To run it in the background instead, add `--detach`; each service's `restart: unless-stopped` starts it again if it exits or Docker restarts: ```bash docker compose -f etc/compose/proxy.yml up --detach docker compose -f etc/compose/proxy.yml logs --follow # follow the stack's logs docker compose -f etc/compose/proxy.yml down # stop and remove the stack ``` ## TLS with Docker Mount your certificate files into the container: ```bash # Proxy with TLS (no mutual auth): docker run --rm \ -p 127.0.0.1:8080:8080 \ -p 50440:50440 \ -p 127.0.0.1:8082:8082 \ -p 127.0.0.1:8092:8092 \ --mount type=bind,source="$(pwd)"/certs,target=/app/certs \ --mount type=bind,source="$(pwd)"/tls.conf,target=/app/tls.conf \ --env PROXY_CONFIG=tls.conf \ --env ADMIN_ENABLED=true \ --env METRICS_ENABLED=true \ pambrose/prometheus-proxy:4.9.0 # Agent with TLS (no mutual auth): docker run --rm \ -p 127.0.0.1:8083:8083 \ -p 127.0.0.1:8093:8093 \ --mount type=bind,source="$(pwd)"/certs,target=/app/certs \ --mount type=bind,source="$(pwd)"/tls.conf,target=/app/tls.conf \ --env AGENT_CONFIG=tls.conf \ --env PROXY_HOSTNAME=proxy-host:50440 \ pambrose/prometheus-agent:4.9.0 ``` Or, on a platform that passes secrets as environment variables, give them as PEM, with no file mounted: ```bash # Proxy with TLS, its certificate and key given as environment variables, no file mounted: docker run --rm \ -p 127.0.0.1:8080:8080 \ -p 50051:50051 \ --env CERT_CHAIN_PEM="$(base64 < server.crt | tr -d '\n')" \ --env PRIVATE_KEY_PEM="$(base64 < server.key | tr -d '\n')" \ pambrose/prometheus-proxy:4.9.0 # Agent trusting the CA that signed the proxy's certificate, given as an environment variable: docker run --rm \ --mount type=bind,source="$(pwd)"/agent.conf,target=/app/agent.conf \ --env AGENT_CONFIG=agent.conf \ --env PROXY_HOSTNAME=proxy-host:50051 \ --env TRUST_CERT_COLLECTION_PEM="$(cat ca.crt)" \ pambrose/prometheus-agent:4.9.0 ``` See [TLS Setup](https://prometheus-proxy.com/security/tls/index.md) for complete TLS configuration details. ## Environment Variables ```text Common environment variables for Docker: Proxy: PROXY_CONFIG - Config file path or URL PROXY_PORT - HTTP listen port (default: 8080) AGENT_PORT - gRPC listen port (default: 50051) ADMIN_ENABLED - Enable admin endpoints (default: false) ADMIN_PORT - Admin port (default: 8092) METRICS_ENABLED - Enable metrics (default: false) METRICS_PORT - Metrics port (default: 8082) SD_ENABLED - Enable service discovery (default: false) SD_PATH - SD endpoint path (default: "discovery") SD_TARGET_PREFIX - SD target prefix Agent: AGENT_CONFIG - Config file path or URL (required) PROXY_HOSTNAME - Proxy hostname (can include :port) AGENT_NAME - Agent name ADMIN_ENABLED - Enable admin endpoints (default: false) ADMIN_PORT - Admin port (default: 8093) METRICS_ENABLED - Enable metrics (default: false) METRICS_PORT - Metrics port (default: 8083) MAX_CONCURRENT_CLIENTS - Parallel scrape limit (default: 1) ``` ## Using the `latest` Tag The `latest` tag always points to the most recent release: ```bash docker pull pambrose/prometheus-proxy:latest docker pull pambrose/prometheus-agent:latest ``` !!! tip "Pin versions in production" Use explicit version tags (e.g., `4.9.0`) in production to avoid unexpected upgrades. --- Source: https://prometheus-proxy.com/kubernetes/ # Kubernetes Run Prometheus Proxy on Kubernetes to scrape metrics from services that live inside firewalled or private clusters. ## Topology The two components play different roles, and that determines where each one runs: - The **agent** runs **inside** each target cluster, alongside the services it scrapes. It opens an **outbound** gRPC connection to the proxy, so the target cluster never needs an inbound firewall rule. - The **proxy** runs **centrally**, next to Prometheus. Agents connect *in* to it on the gRPC port (`50051`), and Prometheus scrapes it on the HTTP port (`8080`). ```mermaid flowchart TB accTitle: The proxy and agent charts in two clusters accDescr { In the monitoring cluster, Prometheus scrapes the proxy on port 8080, and the proxy listens for agents on gRPC port 50051. In the target cluster, behind a firewall, the agent scrapes my-app's /metrics on port 9100 in the cluster and connects out to the proxy over gRPC on port 50051. } %% Each zone's title starts with a line break, which grows the zone to fit it, so the title stands clear of the %% zone's top edge, as in the demos' diagrams. subgraph monitoring["
Monitoring cluster"] prom["Prometheus"] proxy["Prometheus Proxy
:8080 HTTP / :50051 gRPC"] prom -- "scrape :8080" --> proxy end subgraph target["
Target cluster (behind firewall)"] agent["Prometheus Agent"] app["my-app :9100/metrics"] agent -- "scrape in-cluster" --> app end %% The agent connects out to the proxy, so its edge's one arrowhead is at the proxy. The edge is written from the %% proxy, which keeps the agent below it, as a two-way edge whose other arrowhead linkStyle takes off. Written from %% the agent, it needed an invisible link to keep that order, and the layout bent the edge around the link. proxy <-->|"outbound gRPC :50051"| agent linkStyle 2 marker-end:none %% The firewall class draws the target cluster's edge, the firewall, in the accent, and product the proxy's and the %% agent's boxes, as on the home page (javascripts/diagrams.js). class target firewall class proxy,agent product ``` The agent always initiates the connection, so a target cluster only needs **egress** to the proxy's gRPC endpoint — no inbound ports are exposed. !!! tip "See it run" The [Kubernetes Demo](https://prometheus-proxy.com/kubernetes-demo/index.md) builds this topology on one laptop: two kind clusters, the charts below, and an agent whose targets come from annotated Services, without restarting it. !!! note "Namespaces in these examples" The manifests below put the proxy in a `monitoring` namespace and the agent in `default`. Adjust the `namespace` fields and the in-cluster DNS names (e.g. `prometheus-proxy.monitoring.svc.cluster.local`) to match your layout. ## Installing with Helm The repository ships a Helm chart for each side of the firewall, in [`charts/`](https://github.com/pambrose/prometheus-proxy/tree/master/charts): `prometheus-proxy` for the monitoring cluster and `prometheus-agent` for each target cluster. Install them from a clone of the repository: ```bash # In the monitoring cluster, next to Prometheus. agentService adds a LoadBalancer for agents in other clusters. helm install prometheus-proxy ./charts/prometheus-proxy --namespace monitoring --create-namespace \ --set agentService.enabled=true # In each target cluster helm install prometheus-agent ./charts/prometheus-agent -f agent-values.yaml ``` ```yaml # agent-values.yaml proxy: hostname: proxy.example.com:50051 # the proxy's externally reachable gRPC address config: | agent { pathConfigs: [ { name: "My app", path: my_app_metrics, url: "http://my-app.default.svc.cluster.local:8080/metrics" } ] } ``` The charts set up what the manifests below do by hand: the admin-endpoint probes, resource requests, a non-root pod with a read-only root filesystem and no ServiceAccount token (`automountServiceAccountToken`), and optionally a ServiceMonitor (`serviceMonitor.enabled`), an agent token from a Secret (`agentToken.existingSecret`), TLS (`tls.secretName`), each one's dashboard (`dashboard.enabled`, on the pod's loopback only and reached with `kubectl port-forward`, with a login from `dashboard.login.existingSecret`), and, for the agent, a discovery ConfigMap (`discovery.enabled`). A config that holds secrets, such as `proxy.auth` tokens or credentials in an agent's target URLs, can come from a Secret (`existingSecret`) instead of the ConfigMap the chart renders. Each chart's README lists its values. The rest of this page builds the same deployment from plain manifests. ## Deploying the Proxy Deploy the proxy as a `Deployment` plus a `Service`. Admin and metrics endpoints are enabled through environment variables so Kubernetes can probe them and Prometheus can scrape them. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: prometheus-proxy namespace: monitoring labels: app: prometheus-proxy spec: replicas: 1 selector: matchLabels: app: prometheus-proxy template: metadata: labels: app: prometheus-proxy spec: containers: - name: proxy image: pambrose/prometheus-proxy:4.9.0 ports: - { name: http, containerPort: 8080 } # Prometheus scrapes here - { name: grpc, containerPort: 50051 } # agents connect here - { name: metrics, containerPort: 8082 } - { name: admin, containerPort: 8092 } env: - { name: ADMIN_ENABLED, value: "true" } - { name: METRICS_ENABLED, value: "true" } livenessProbe: httpGet: { path: /ping, port: admin } initialDelaySeconds: 10 periodSeconds: 15 readinessProbe: httpGet: { path: /ping, port: admin } # not /healthcheck, which measures load initialDelaySeconds: 10 periodSeconds: 15 resources: requests: { cpu: 100m, memory: 256Mi } limits: { memory: 512Mi } --- apiVersion: v1 kind: Service metadata: name: prometheus-proxy namespace: monitoring labels: app: prometheus-proxy spec: selector: app: prometheus-proxy ports: - { name: http, port: 8080, targetPort: http } - { name: grpc, port: 50051, targetPort: grpc } - { name: metrics, port: 8082, targetPort: metrics } ``` The `Service` above is a `ClusterIP`, which is enough when Prometheus and the agents live in the same cluster. Prometheus reaches the proxy at `prometheus-proxy.monitoring.svc.cluster.local:8080`, and same-cluster agents can use the same DNS name for the gRPC port. ### Exposing gRPC to Remote Agents When agents run in **other** clusters, they need to reach the proxy's gRPC port from outside. Expose it with a `LoadBalancer` Service (or an Ingress controller): ```yaml apiVersion: v1 kind: Service metadata: name: prometheus-proxy-grpc namespace: monitoring labels: app: prometheus-proxy spec: type: LoadBalancer selector: app: prometheus-proxy ports: - { name: grpc, port: 50051, targetPort: grpc } ``` !!! warning "gRPC needs HTTP/2 end to end" gRPC runs over HTTP/2. A plain `LoadBalancer` (L4) forwards it transparently. If you put an Ingress in front instead, it must support HTTP/2 / gRPC backends (for example, the NGINX Ingress `nginx.ingress.kubernetes.io/backend-protocol: GRPC` annotation). On NGINX Ingress, also set `nginx.ingress.kubernetes.io/proxy-body-size: "0"`: its default, 1 MB, cuts off every agent each time its results add up to a megabyte, as [nginx Reverse Proxy](https://prometheus-proxy.com/advanced/index.md#nginx-reverse-proxy) explains. Terminate or pass through TLS as described under [TLS](#tls). With an agent or a proxy from 4.6.0 or earlier, also raise the Ingress's stream timeouts, as [nginx Reverse Proxy](https://prometheus-proxy.com/advanced/index.md#nginx-reverse-proxy) explains: on NGINX Ingress, the `nginx.ingress.kubernetes.io/proxy-read-timeout` annotation and the controller ConfigMap's `client-body-timeout`. ## Deploying the Agent The agent's path mappings live in a `ConfigMap`. The proxy hostname is supplied separately through the `PROXY_HOSTNAME` environment variable, so the same config works regardless of where the proxy is exposed. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: prometheus-agent-config namespace: default data: agent.conf: | agent { pathConfigs: [ { name: "My App metrics" path: my_app_metrics url: "http://my-app.default.svc.cluster.local:8080/metrics" } ] } ``` Each entry in `pathConfigs` maps a proxy `path` (what Prometheus scrapes) to the in-cluster `url` the agent fetches from. Point `url` at a Kubernetes Service DNS name such as `http://my-app.default.svc.cluster.local:8080/metrics`. ### Updating Targets without Restarting the Agent With `pathConfigs` alone, changing the target list means updating the `ConfigMap` **and restarting the agent pod** — which interrupts scraping for every path the agent serves, not just the one that changed. [Dynamic target discovery](https://prometheus-proxy.com/configuration/agent/index.md#dynamic-target-discovery) removes the restart: mount a *second* `ConfigMap` holding a `paths` list and point `agent.discovery` at it. The agent re-reads the file on an interval and reconciles — targets added to the `ConfigMap` start scraping within the interval, removed ones unregister, and untouched paths never stop. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: agent-targets data: targets.conf: | paths = [ { name = "app1", path = "app1_metrics", url = "http://app1.default.svc.cluster.local:9090/metrics" } { name = "app2", path = "app2_metrics", url = "http://app2.default.svc.cluster.local:9090/metrics" } ] ``` Mount it into the agent pod (e.g. at `/etc/prometheus-proxy/targets.conf`) and enable discovery in the agent's main config: ```hocon agent { discovery { enabled = true file.path = "/etc/prometheus-proxy/targets.conf" reconcileIntervalSecs = 30 } } ``` Discovery **polls** the file rather than using inotify precisely because of how Kubernetes delivers `ConfigMap` updates (atomic symlink swaps that file watchers often miss). Note that a kubelet can take up to a minute to propagate a `ConfigMap` change to the mounted volume — that delay is Kubernetes's, and comes on top of the reconcile interval. A malformed or half-propagated file is skipped, keeping the last-known-good target set, so a bad edit never tears down working targets, even when the agent reconnects to the proxy while the file is still bad. Keep discovery targets in a **separate** `ConfigMap` from the agent's main config: whatever automation writes the target list then can't touch ports, TLS, or the proxy address. ### Standalone Deployment The common pattern is a single agent Deployment per cluster that scrapes several in-cluster endpoints: ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: prometheus-agent namespace: default labels: app: prometheus-agent spec: replicas: 1 selector: matchLabels: app: prometheus-agent template: metadata: labels: app: prometheus-agent spec: containers: - name: agent image: pambrose/prometheus-agent:4.9.0 ports: - { name: metrics, containerPort: 8083 } - { name: admin, containerPort: 8093 } env: - name: PROXY_HOSTNAME value: "proxy.example.com:50051" # the proxy's externally reachable address - { name: AGENT_CONFIG, value: /app/agent.conf } - { name: ADMIN_ENABLED, value: "true" } - { name: METRICS_ENABLED, value: "true" } volumeMounts: - { name: config, mountPath: /app/agent.conf, subPath: agent.conf } livenessProbe: httpGet: { path: /ping, port: admin } initialDelaySeconds: 10 periodSeconds: 15 readinessProbe: httpGet: { path: /healthcheck, port: admin } initialDelaySeconds: 10 periodSeconds: 15 resources: requests: { cpu: 100m, memory: 256Mi } limits: { memory: 512Mi } volumes: - name: config configMap: name: prometheus-agent-config ``` Set `PROXY_HOSTNAME` to the proxy's externally reachable address (the `LoadBalancer` host from [above](#exposing-grpc-to-remote-agents)), including the gRPC port if it is not the default `50051`. Keep it at one replica, as above, or the agent chart's `replicaCount: 1`. Every replica runs the same config and registers the same paths: without consolidated mode the last to register serves them and the others sit idle, and with it the proxy joins their answers, so Prometheus gets every series once per replica and drops the duplicates, logging an error for each target on every scrape. Kubernetes replaces a failed agent pod on its own, in about a second in the [Kubernetes Demo](https://prometheus-proxy.com/kubernetes-demo/index.md); see [Consolidated Mode](https://prometheus-proxy.com/advanced/index.md#consolidated-mode). ### Sidecar Alternatively, run the agent as a sidecar next to a single application pod and scrape it over `localhost`: ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: my-app namespace: default labels: app: my-app spec: replicas: 1 selector: matchLabels: app: my-app template: metadata: labels: app: my-app spec: containers: - name: my-app image: my-app:latest ports: - { name: metrics, containerPort: 9100 } - name: prometheus-agent image: pambrose/prometheus-agent:4.9.0 env: - { name: PROXY_HOSTNAME, value: "proxy.example.com:50051" } - { name: AGENT_CONFIG, value: /app/agent.conf } volumeMounts: - { name: agent-config, mountPath: /app/agent.conf, subPath: agent.conf } volumes: - name: agent-config configMap: name: prometheus-agent-config # with its agent.conf url changed to http://localhost:9100/metrics ``` With the sidecar pattern the agent's `url` should point at `http://localhost:9100/metrics` rather than a Service DNS name. !!! tip "Native sidecar containers" On Kubernetes 1.29+ you can run the agent as a native sidecar — an entry in `initContainers` with `restartPolicy: Always` — so it starts before the app container and is tracked by the pod's lifecycle. The plain multi-container form above works on all versions. ## Prometheus Integration Prometheus scrapes the **proxy**, using the agent `path` as the `metrics_path`. The path must match the `path` value from the agent `ConfigMap`. === "Scrape config" Add a job to `prometheus.yml` pointing at the proxy Service: ```yaml scrape_configs: - job_name: 'my-app-via-proxy' metrics_path: '/my_app_metrics' static_configs: - targets: ['prometheus-proxy.monitoring.svc.cluster.local:8080'] ``` === "ServiceMonitor (Operator)" If you run the Prometheus Operator (e.g. `kube-prometheus-stack`), use a `ServiceMonitor` instead: ```yaml apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: name: prometheus-proxy namespace: monitoring labels: release: kube-prometheus-stack # must match your Prometheus serviceMonitorSelector spec: selector: matchLabels: app: prometheus-proxy endpoints: # Add one endpoint per registered proxy path. - port: http path: /my_app_metrics interval: 30s ``` The `release` label must match your Prometheus instance's `serviceMonitorSelector`. Add one entry under `endpoints` for each registered proxy path. !!! tip "Dynamic path discovery" Rather than listing every path by hand, enable the proxy's service-discovery endpoint and let Prometheus pull the target list with `http_sd_config`. See [Prometheus Service Discovery](https://prometheus-proxy.com/service-discovery/index.md). (This is the *Prometheus-facing* half; the *agent-facing* half — picking up target changes inside the cluster without a restart — is [dynamic target discovery above](#updating-targets-without-restarting-the-agent). The two compose: discovered paths appear in the service-discovery output like any other. **Caveat:** if you run an [HA proxy pair](https://prometheus-proxy.com/production/index.md#high-availability), scrape with `static_config` instead — a standby proxy returns an empty discovery list, which `http_sd_config` treats as "delete these targets".) ## TLS To secure the proxy ↔ agent gRPC channel, bundle the proxy's certificate files into a `Secret` and mount it into the proxy container: ```bash # Bundle the proxy's certificate and key, and for mutual TLS the CA that signed the agents', into a Secret: kubectl create secret generic prometheus-proxy-tls \ --namespace monitoring \ --from-file=cert.pem \ --from-file=key.pem \ --from-file=ca.pem ``` ```yaml # Proxy container spec excerpt — point the proxy at the mounted files: env: - { name: CERT_CHAIN_FILE_PATH, value: /app/certs/cert.pem } - { name: PRIVATE_KEY_FILE_PATH, value: /app/certs/key.pem } - { name: TRUST_CERT_COLLECTION_FILE_PATH, value: /app/certs/ca.pem } # mutual TLS only volumeMounts: - { name: tls, mountPath: /app/certs, readOnly: true } volumes: - name: tls secret: secretName: prometheus-proxy-tls ``` The environment variables point the proxy at the files under `/app/certs`. `TRUST_CERT_COLLECTION_FILE_PATH` turns on mutual TLS; leave it out for TLS without client certificates. The agent needs a separate `Secret`, in its namespace: the CA that signed the proxy's certificate, plus a client certificate and key for mutual TLS, given in the same three variables. Each chart's `tls` values (`tls.secretName` and the file names in it) set this up from such a `Secret`. See [TLS Setup](https://prometheus-proxy.com/security/tls/index.md) for the full configuration, including mutual authentication. The [Kubernetes Demo](https://prometheus-proxy.com/kubernetes-demo/index.md#mutual-tls-refuses-an-agent-without-a-certificate) runs both charts with mutual TLS, from Secrets it makes with `openssl`, and shows the proxy refusing an agent without a client certificate. ## Health Probes & Resources The proxy and agent Deployments above wire Kubernetes probes to the admin endpoints: | Probe | Proxy | Agent | |:-----------------|:------------|:-------------------| | `livenessProbe` | `GET /ping` | `GET /ping` | | `readinessProbe` | `GET /ping` | `GET /healthcheck` | `/ping` returns `pong` while the process is up. `/healthcheck` returns each health check's status, and a non-200 when any is unhealthy. The proxy's readiness probe is `/ping` because its `/healthcheck` measures load. Each agent stays connected to one proxy pod, so taking a busy pod out of the Service doesn't move its load elsewhere: the scrapes for its agents' targets fail until it's ready again. Alert on the proxy's `/healthcheck` instead. It turns unhealthy when the scrapes or chunked transfers in flight reach 80% of `maxInFlightScrapeRequests`, or one agent's queue reaches `scrapeRequestBacklogUnhealthySize`. Both endpoints are served on the **admin** port (`8092` for the proxy, `8093` for the agent), which requires `ADMIN_ENABLED=true`. The manifests also set conservative CPU/memory `requests` and `limits` — tune them to your scrape volume and payload sizes. ## Next Steps
- [Agent Configuration](https://prometheus-proxy.com/configuration/agent/index.md) Path configs, HTTP client tuning, and scrape options - [Security & TLS](https://prometheus-proxy.com/security/index.md) Secure the proxy-agent channel with TLS and mutual authentication - [Prometheus Service Discovery](https://prometheus-proxy.com/service-discovery/index.md) Let Prometheus discover proxied targets dynamically - [Monitoring](https://prometheus-proxy.com/monitoring/index.md) Scrape the proxy's and agent's operational metrics
--- Source: https://prometheus-proxy.com/cloud-platforms/ # Cloud Platforms An app on a platform such as ECS, Cloud Run, or Azure Container Apps can't be scraped by a Prometheus outside the platform without opening its metrics to the internet. An [embedded agent](https://prometheus-proxy.com/embedded-agent/index.md) reverses the direction: it connects to a proxy beside Prometheus, and answers each scrape by reading the app's `/metrics`. This page sets that up for a JVM app, with the proxy on AWS, GCP, Azure, DigitalOcean, or Railway. The [Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md) runs the same setup on one machine. ```text App platform (ECS, Cloud Run, ...) Proxy host (AWS, GCP, Azure, DigitalOcean, Railway) app: /metrics on 127.0.0.1 prometheus-proxy :50051 agents, over TLS with a token └ embedded agent ── gRPC, TLS + token ─────► :8080 scrapes, private Prometheus ── scrapes :8080/my_app_metrics ``` ## How It Fits Together - The agent runs inside the app and connects out to the proxy's agent port, so the app opens no port, and nothing outside reaches into the platform. - It answers each scrape by reading the app's `/metrics` on `127.0.0.1`. If that endpoint asks for Basic Auth, the agent sends the credentials with each scrape and leaves them out of its logs. - Prometheus scrapes the proxy, on a private network, at the path the agent registered. Keep the proxy's scrape port (8080) off the internet: anyone who reaches it scrapes through the agent. Only the agent port (50051) is public, behind TLS and a token. - Keep the proxy's [dashboard](https://prometheus-proxy.com/web-dashboard/index.md) behind a [login](https://prometheus-proxy.com/web-dashboard/index.md#login) and on the private network: without a login, it has no authentication. The example below turns it on, with the apps' agents' dashboards [relayed](https://prometheus-proxy.com/screens-page/index.md#agent-screens) to its screens page, so the apps open no port for them, and publishes it on the VM's loopback only, which you reach with an SSH tunnel. ## In the App ### Starting the Agent Build the agent's settings in code from the app's settings, with [`embeddedAgent { }` or `EmbeddedAgentConfig.builder()`](https://prometheus-proxy.com/embedded-agent/index.md#configuring-in-code), so no file holds the token or the password, and start it: === "Kotlin" ```kotlin import io.prometheus.agent.EmbeddedAgentInfo import io.prometheus.agent.embeddedAgent import kotlin.time.Duration.Companion.seconds // Starts the agent from the app's own settings, in memory, so no config file holds the token or the password. Returns // null when the agent is off, without PROMETHEUS_PROXY, or can't start, which it logs: the app's metrics aren't worth // an outage. fun startPrometheusAgent( appVersion: String, appPort: Int, ): EmbeddedAgentInfo? = embeddedAgent { // The version tells the old and new revisions apart during a deploy name = "my-app-$appVersion" // The proxy, its token, and its certificate: PROMETHEUS_PROXY, PROMETHEUS_AGENT_TOKEN, and PROMETHEUS_PROXY_CERT fromEnvironment() // The app's own /metrics, on 127.0.0.1; the agent sends the credentials as Basic Auth scrapeSelf( path = "my_app_metrics", port = appPort, username = env("METRICS_USER"), password = env("METRICS_PASSWORD"), ) // How long the agent's stop may hold up the app's shutdown: inside the platform's window after SIGTERM, such as // Cloud Run's 10 seconds stopTimeout = 8.seconds }.startIfConfigured(logBanner = false) private fun env(name: String) = System.getenv(name).orEmpty().trim() ``` === "Java" ```java import io.prometheus.agent.EmbeddedAgentConfig; import io.prometheus.agent.EmbeddedAgentInfo; import java.time.Duration; public class EmbeddedAgentConfigJavaExample { // Starts the agent from the app's own settings, in memory, so no config file holds the token or the password. // Returns null when the agent is off, without PROMETHEUS_PROXY, or can't start, which it logs: the app's metrics // aren't worth an outage. public static EmbeddedAgentInfo startPrometheusAgent(String appVersion, int appPort) { return EmbeddedAgentConfig.builder() // The version tells the old and new revisions apart during a deploy .name("my-app-" + appVersion) // The proxy, its token, and its certificate: PROMETHEUS_PROXY, PROMETHEUS_AGENT_TOKEN, and PROMETHEUS_PROXY_CERT .fromEnvironment() // The app's own /metrics, on 127.0.0.1; the agent sends the credentials as Basic Auth .scrapeSelf("my_app_metrics", appPort, env("METRICS_USER"), env("METRICS_PASSWORD")) // How long the agent's stop may hold up the app's shutdown: inside the platform's window after SIGTERM, such as // Cloud Run's 10 seconds .stopTimeout(Duration.ofSeconds(8)) .build() .startIfConfigured(false); } private static String env(String name) { String value = System.getenv(name); return value == null ? "" : value.trim(); } } ``` - The app's settings are `PROMETHEUS_PROXY` (the proxy's agent port, as `host:port`), `PROMETHEUS_AGENT_TOKEN`, and `PROMETHEUS_PROXY_CERT` (the proxy's certificate, as PEM or its base64), which [`fromEnvironment()`](https://prometheus-proxy.com/embedded-agent/index.md#settings-from-the-environment) reads, with the certificate checked against `prometheus-proxy`, the name [Securing the Link](#securing-the-link) issues it to (`PROMETHEUS_PROXY_AUTHORITY` for another), and `METRICS_USER` and `METRICS_PASSWORD` for the app's `/metrics`. Without `PROMETHEUS_PROXY`, as on a developer's machine, `startIfConfigured()` leaves the agent off. - The agent reads its standard environment variables too, such as `AGENT_TOKEN` and `PROXY_HOSTNAME`, and they take precedence over the config, so keep those names out of the app's environment unless you mean the agent to use them. - The app's version in `agent.name` tells the old and new revisions apart in the proxy's logs during a deploy. - The agent's admin and metrics servers stay off, as they are unless asked for, since the app has no port to spare for them. [`agentMetricsAt`](https://prometheus-proxy.com/embedded-agent/index.md#the-agents-own-metrics) serves the agent's own metrics through the proxy instead, with no port. - `scrapeSelf` percent-encodes the credentials into the scrape URL, so a password with any character works. An app with a metrics registry needn't serve it at all: `source(path, registry)` has the agent [read it in-process](https://prometheus-proxy.com/embedded-agent/index.md#metrics-served-in-process). - A failure to start is logged, and the app carries on without the agent: its metrics aren't worth an outage. To hear of one somewhere someone will see it, such as a chat channel, add a handler with the builder's [`onFailure`](https://prometheus-proxy.com/embedded-agent/index.md#starting-where-theres-a-proxy), which is given why, as the log line has it. ### Starting and Stopping It with the App Start the agent once the app serves `/metrics`, and stop it when the app stops. In a Ktor module: ```kotlin fun Application.module() { routing { get("/metrics") { call.respondText("my_app_up 1\n") } } // Started once the routes are in place, so the agent's first scrape finds /metrics val agent = startPrometheusAgent(appVersion = "1.0.0", appPort = 8080) // Stopped once the application has stopped. In development mode, a reload stops the old application, and its // agent with it, before the new one starts its own. monitor.subscribe(ApplicationStopped) { agent?.shutdown() } } ``` In Spring Boot, the [Spring Boot Starter](https://prometheus-proxy.com/spring-boot-starter/index.md) starts and stops it with the app, as the [Spring Boot Demo](https://prometheus-proxy.com/spring-boot-demo/index.md) shows; [Without the Starter](https://prometheus-proxy.com/spring-boot-starter/index.md#without-the-starter) covers doing it with a bean you write. The platform stops the app with `SIGTERM`, then kills it once its shutdown window is up: 10 seconds on Cloud Run. Set the builder's [`stopTimeout`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo) inside that window, as the example above does, so the rest of the app's shutdown isn't left waiting on the agent: once it's up, `shutdown()` returns, with a warning, and the agent goes on stopping on its own. The [Ktor Plugin](https://prometheus-proxy.com/ktor-plugin/index.md#a-failed-start-and-the-stop) and the Spring Boot Starter take it as their `stop-timeout`, 30 seconds by default, longer than Cloud Run's window. Keep the agent out of the health check the platform restarts the app on. The app serves without its agent, which reconnects by itself once the proxy is back, so a failed check would only restart a working app. To see whether the agent is connected, report [`EmbeddedAgentInfo`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo)'s `isConnected` and `proxyEndpoint` somewhere that doesn't fail the check, such as a detail of the app's status page; the Spring Boot Demo reports them in Actuator's health as UNKNOWN, not DOWN. Give the app's logging configuration the level the standalone agent sets for gRPC's internal logging; see [Logging](https://prometheus-proxy.com/embedded-debugging/index.md#logging). ### Packaging the App The agent is a library inside the app, so the app's image is an ordinary JVM image. It adds nothing for the agent: no port, since the agent connects out to the proxy, and no file, since the token and the certificate come in as environment variables. A two-stage Dockerfile, for a Gradle app named `my-app` that uses the `application` plugin: ```dockerfile # Build the app with its own Gradle wrapper, on a JDK, keeping Gradle's downloads between builds FROM eclipse-temurin:25-jdk-noble AS build WORKDIR /src COPY . . RUN --mount=type=cache,target=/root/.gradle ./gradlew --no-daemon installDist # Run it on a JRE, as a user that isn't root, named by number FROM eclipse-temurin:25-jre-noble RUN useradd --system --uid 1001 --home-dir /app app COPY --from=build /src/build/install/my-app /app USER 1001 # Lets Netty, which the agent's gRPC runs on, load its native TLS library and use sun.misc.Unsafe on Java 24 and later, # and sizes the heap from the container's memory ENV JAVA_OPTS="-XX:MaxRAMPercentage=75 --enable-native-access=ALL-UNNAMED --sun-misc-unsafe-memory-access=allow" # The app's own port; the agent opens none, since it connects out to the proxy EXPOSE 8080 ENTRYPOINT ["/app/bin/my-app"] ``` - It builds with the app's Gradle wrapper on a JDK, and runs the result on a JRE as a user that isn't root, named by number, so a platform that checks for one, such as Kubernetes with `runAsNonRoot`, can. Add a `.dockerignore` that leaves out `build/`, `.gradle/`, `.kotlin/`, `.git/`, and `.idea/`, so `COPY . .` sends only the sources, and a commit or an IDE doesn't make the next build start over. - The start script `installDist` writes reads `JAVA_OPTS`. Besides sizing the heap from the container's memory, it carries two flags for Netty, which the agent's gRPC runs on, on Java 24 and later. The stock images run with the second; their jars ask for native access in their manifest instead of the first, which only `java -jar` reads: - `--enable-native-access=ALL-UNNAMED` lets Netty load its native TLS library without the warning Java prints, which says a later release will block the call. - `--sun-misc-unsafe-memory-access=allow` lets Netty use `sun.misc.Unsafe` for its buffers, which it otherwise does without. Java 22 and earlier don't know it and won't start with it, so leave it out there. - An app built as a fat JAR starts with `java -jar`, which doesn't read `JAVA_OPTS`: give the options in `JDK_JAVA_OPTIONS`, which the `java` launcher reads, or on its command line. - Any JDK 17 or later runs the agent; the stock images run 25. The [Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md)'s coffee shop is built the same way. ### What the App Platform Must Give It - **CPU between requests, and an instance that stays up.** The agent holds its connection to the proxy open between scrapes, so a platform that throttles CPU outside requests, or scales the app to zero, stalls it. - On AWS, run the app as an ECS service on Fargate, whose tasks keep their CPU whether or not they handle requests. App Runner gives an instance CPU only while it handles requests, and bills an idle one for its memory alone, so the agent stalls there. - On GCP, Cloud Run needs instance-based billing with a minimum instance: ```bash gcloud run services update my-app --no-cpu-throttling --min-instances=1 ``` - On Azure, Container Apps scales an app to zero by default, so keep a replica running: ```bash az containerapp update --name my-app --resource-group my-group --min-replicas 1 ``` On App Service, turn on Always On, which keeps the app loaded when it has no requests. - **One instance per path.** Each agent registers its path as its own, and the last one to register serves it, so a second instance's agent takes the path from the first. Run one instance (a desired count of 1 for an ECS service, `--max-instances=1` on Cloud Run, `--max-replicas 1` on Container Apps), or make the agents [consolidated](https://prometheus-proxy.com/advanced/index.md#consolidated-mode) and give each instance's series a distinct label, such as a common tag with the instance's ID: the proxy merges the instances' answers into one scrape, and without the label it would repeat each series once per instance. - **Deploys need nothing more.** While the old and new revisions overlap, the new revision's agent takes the path over, and the old one stops with its app. ## Securing the Link The agent port faces the internet, so the agents connect over TLS and present a token. Make a certificate for the proxy, issued to a fixed name rather than to whatever host name the platform gives it, and a token: ```bash openssl req -x509 -newkey rsa:3072 -nodes -days 3650 -subj "/CN=prometheus-proxy" \ -addext "subjectAltName=DNS:prometheus-proxy" -keyout server.key -out server.crt openssl rand -hex 32 > agent-token ``` - The proxy takes `server.crt` and `server.key` as `CERT_CHAIN_PEM` and `PRIVATE_KEY_PEM`, and the token as `AGENT_TOKEN`. - The agent trusts `server.crt` (`agent.tls.trustCertCollectionPem`), checks it against the fixed name (`agent.tls.overrideAuthority = "prometheus-proxy"`), and presents the token (`agent.agentToken`): `fromEnvironment()` sets all three from `PROMETHEUS_PROXY_CERT` and `PROMETHEUS_AGENT_TOKEN`, with `prometheus-proxy` as the name. - A variable field that takes one line takes the certificate and key as base64: `base64 < server.crt | tr -d '\n'`. See [Certificates as Environment Variables](https://prometheus-proxy.com/security/tls/index.md#certificates-as-environment-variables) for the forms a PEM setting takes. - Keep `server.key` and the token out of version control. To limit which paths each app may register, give each its own identity instead of one shared token; see [Per-agent identities](https://prometheus-proxy.com/security/index.md#per-agent-identities-and-path-authorization). ## Where to Run the Proxy The proxy and Prometheus run together, on a host whose agent port the apps can reach: | Platform | Agents reach the proxy through | Prometheus runs | |:-------------|:------------------------------------------------------|:-------------------------------------------| | AWS | An EC2 instance's address, with a security group rule | On the instance, beside the proxy | | GCP | A Compute Engine VM's address, with a firewall rule | On the VM, beside the proxy | | Azure | An Azure VM's address, with a network security rule | On the VM, beside the proxy | | DigitalOcean | A Droplet's address, with a firewall open on 50051 | On the Droplet, beside the proxy | | Railway | A TCP Proxy on the proxy service's port 50051 | As another service, on the private network | [`examples/cloud-proxy`](https://github.com/pambrose/prometheus-proxy/tree/master/examples/cloud-proxy) holds the proxy's config and a Prometheus config for each of them, and a Compose file that runs both on a VM: === "docker-compose.yml" ```yaml # A prometheus-proxy and a Prometheus that scrapes through it, on a VM that agents embedded in cloud apps connect to, # such as an EC2 instance, a Compute Engine instance, an Azure VM, or a DigitalOcean Droplet. The setup is described at # https://prometheus-proxy.com/cloud-platforms/ # # Put the proxy's certificate and key, as base64, the agents' token, and the dashboard's password in a .env file beside # this one, and keep it out of version control: # # CERT_CHAIN_PEM= # PRIVATE_KEY_PEM= # AGENT_TOKEN= # DASHBOARD_PASSWORD= # # then run `docker compose up --detach` here. Only the agents' port, 50051, is published to the internet; let it, and # nothing else, through the host's firewall. The dashboard's port, 8094, and Prometheus's, 9090, are published on this # host only: reach them with an SSH tunnel, such as `ssh -L 8094:localhost:8094 -L 9090:localhost:9090 `. services: proxy: image: pambrose/prometheus-proxy:4.9.0 ports: - "50051:50051" # gRPC, for the agents: TLS and the token - "127.0.0.1:8094:8094" # The dashboard, on this host only: reach it with an SSH tunnel environment: PROXY_CONFIG: /app/proxy.conf CERT_CHAIN_PEM: ${CERT_CHAIN_PEM:?set CERT_CHAIN_PEM in .env} PRIVATE_KEY_PEM: ${PRIVATE_KEY_PEM:?set PRIVATE_KEY_PEM in .env} AGENT_TOKEN: ${AGENT_TOKEN:?set AGENT_TOKEN in .env} DASHBOARD_PASSWORD: ${DASHBOARD_PASSWORD:?set DASHBOARD_PASSWORD in .env} volumes: - ./proxy.conf:/app/proxy.conf:ro restart: unless-stopped prometheus: image: prom/prometheus:v3.14.0 ports: - "127.0.0.1:9090:9090" # On this host only: reach it with an SSH tunnel, or run Grafana beside it volumes: - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro - prometheus-data:/prometheus depends_on: - proxy restart: unless-stopped volumes: prometheus-data: ``` === "proxy.conf" ```hocon // A proxy that agents embedded in cloud apps connect to. Its certificate, key, and the agents' token come from the // environment (CERT_CHAIN_PEM, PRIVATE_KEY_PEM, AGENT_TOKEN), so this file holds no secret. The setup is described at // https://prometheus-proxy.com/cloud-platforms/ proxy { // Prometheus scrapes the apps' metrics here. Keep it off the internet: anyone who reaches it scrapes through the // agents http.port = 8080 // The agents connect here, over TLS and with the token: the one port to open to the internet agent.port = 50051 // The proxy's own metrics, which Prometheus scrapes too: how many agents are connected, and how their scrapes go metrics { enabled = true port = 8082 } // The dashboard, with each connected app's agent dashboard relayed to its screens page through the agent's // connection (agentScreens), so the apps open no port. Its login is DASHBOARD_PASSWORD, with the username admin. It // listens on every interface in its container, which the Compose file publishes on the VM's loopback only: reach it // at http://localhost:8094/ through an SSH tunnel dashboard { enabled = true port = 8094 agentScreens = true } } ``` === "prometheus.yml" ```yaml # Prometheus beside the proxy. It reaches the proxy on the compose network, where the proxy serves each app's metrics # at the path its agent registered. The setup is described at # https://prometheus-proxy.com/cloud-platforms/ global: scrape_interval: 30s scrape_configs: # The app's metrics, which its embedded agent registered as my_app_metrics. Prometheus sends its scrape timeout along, # and the agent stops the app's scrape at it. - job_name: my-app metrics_path: /my_app_metrics static_configs: - targets: [ 'proxy:8080' ] relabel_configs: # Name the app, not the proxy its metrics come through - target_label: instance replacement: my-app # The proxy's own metrics: proxy_agent_map_size counts the connected agents - job_name: prometheus-proxy static_configs: - targets: [ 'proxy:8082' ] ``` ### AWS - On an EC2 instance with Docker, copy `examples/cloud-proxy` over, put the certificate, key, token, and dashboard password in its `.env`, and run `docker compose up --detach`. Open the agent port in the instance's security group: ```bash aws ec2 authorize-security-group-ingress --group-id sg-0123456789abcdef0 --protocol tcp --port 50051 \ --cidr 0.0.0.0/0 ``` - An app on ECS in the same VPC can reach the instance on its private address instead: admit the app's security group (`--source-group` in place of `--cidr`), so the agent port needn't face the internet at all. Keep the token and TLS anyway. - To run the proxy on ECS on Fargate, as a service with one task, put a [Network Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-listeners.html) in front of it with a TCP listener on 50051. A TCP listener forwards the connection as it is, so the proxy terminates TLS, and the agent's heartbeat, which it sends whenever the connection has been idle for a few seconds, keeps the connection inside the listener's idle timeout. Run Prometheus as another service that reaches the proxy's scrape port inside the VPC. - On EKS, see [Kubernetes](https://prometheus-proxy.com/kubernetes/index.md). ### GCP - On a Compute Engine VM with Docker, copy `examples/cloud-proxy` over, put the certificate, key, token, and dashboard password in its `.env`, and run `docker compose up --detach`. Open the agent port with a firewall rule that applies to the VM's network tag: ```bash gcloud compute firewall-rules create prometheus-proxy-agents --allow=tcp:50051 --target-tags=prometheus-proxy gcloud compute instances add-tags my-proxy-vm --tags=prometheus-proxy --zone=us-central1-a ``` - An app on Cloud Run in the same project can reach the VM on its internal address instead, through [Direct VPC egress](https://docs.cloud.google.com/run/docs/configuring/vpc-direct-vpc), so the agent port needn't face the internet at all. Keep the token and TLS anyway. - On GKE, see [Kubernetes](https://prometheus-proxy.com/kubernetes/index.md). - The proxy can run on [Cloud Run](https://docs.cloud.google.com/run/docs/triggering/grpc) too, with constraints. A Cloud Run service receives traffic on one port, so that port is the agent port (`--port=50051`), served over end-to-end HTTP/2 (`--use-http2`) with TLS from Google's front end, and Prometheus runs as a sidecar that scrapes the proxy on `localhost:8080`. The front end is a reverse proxy, so turn the [transport filter](https://prometheus-proxy.com/advanced/index.md#nginx-reverse-proxy) off on both sides. Its certificate comes from a public CA, so the agent dials the service's host on port 443 and trusts a CA bundle in place of `server.crt`, with no authority override, as with [TLS at nginx](https://prometheus-proxy.com/advanced/index.md#tls-at-nginx). The agent's stream ends at the service's request timeout, at most 60 minutes, and the agent reconnects. The proxy needs the same single, always-on instance as the app. A VM is simpler. ### Azure - On an Azure VM with Docker, copy `examples/cloud-proxy` over, put the certificate, key, token, and dashboard password in its `.env`, and run `docker compose up --detach`. Open the agent port in the VM's network security group with [`az vm open-port`](https://learn.microsoft.com/en-us/cli/azure/vm?view=azure-cli-latest), which admits it from any source; for a narrower one, add the rule with `az network nsg rule create` instead: ```bash az vm open-port --resource-group my-group --name my-proxy-vm --port 50051 ``` - An app on Container Apps, in an environment with a virtual network that reaches the VM's, can reach the VM on its private address instead, so the agent port needn't face the internet at all. Keep the token and TLS anyway. - On AKS, see [Kubernetes](https://prometheus-proxy.com/kubernetes/index.md). - The proxy can run on [Container Apps](https://learn.microsoft.com/en-us/azure/container-apps/ingress-overview) too, as an app with one replica. External TCP ingress on port 50051 forwards the agent's connection as it is, so the proxy terminates TLS; Container Apps offers it only in an environment with a virtual network. Run Prometheus as another app in the environment, and give it the proxy's scrape port as an additional, internal TCP port. ### DigitalOcean - On a Droplet with Docker, copy `examples/cloud-proxy` over, put the certificate, key, token, and dashboard password in its `.env`, and run `docker compose up --detach`. Give the Droplet a [Cloud Firewall](https://docs.digitalocean.com/products/networking/firewalls/) that admits only port 50051, and SSH from your address. - App Platform is a poorer fit. DigitalOcean documents [HTTP/2 for its services](https://docs.digitalocean.com/products/app-platform/how-to/configure-http2/), which gRPC needs, but its [limits page](https://docs.digitalocean.com/products/app-platform/details/limits/) says it doesn't support gRPC. Its edge is also a reverse proxy, which needs the [transport filter](https://prometheus-proxy.com/advanced/index.md#nginx-reverse-proxy) off on both sides and, as on Cloud Run, a CA bundle for the agent to trust. Try it with your app before relying on it. - On DigitalOcean Kubernetes, see [Kubernetes](https://prometheus-proxy.com/kubernetes/index.md). ### Railway - Railway's HTTPS domains don't carry the agent's gRPC through to the container, so give the proxy service a [TCP Proxy](https://docs.railway.com/networking/tcp-proxy) on port 50051, and no HTTPS domain. Railway gives it a host and port, such as `shuttle.proxy.rlwy.net:15140`, which is the agent's `PROMETHEUS_PROXY`. - The TCP Proxy forwards the connection as it is and adds no TLS, so the proxy terminates it: deploy the `pambrose/prometheus-proxy` image, 4.6.0 or later, and set `CERT_CHAIN_PEM`, `PRIVATE_KEY_PEM`, and `AGENT_TOKEN` as the service's variables, with `METRICS_ENABLED=true` for the proxy's own metrics. The image needs no config file for this. - Name the service `prometheus-proxy`, so Prometheus reaches it at `prometheus-proxy.railway.internal:8080` on the [private network](https://docs.railway.com/networking/private-networking). In an older environment, whose private network carries IPv6 only, set the proxy's `proxy.http.host` to `"::"`, in a config it reads through `PROXY_CONFIG`, so Prometheus can reach the scrape port. - Run Prometheus as another service, built from a Dockerfile that copies in a `prometheus.yml` like the example's, with its targets on `prometheus-proxy.railway.internal`, and a volume for its data. ## On the Prometheus Side The example's `prometheus.yml` scrapes the app's metrics at the path its agent registered, `/my_app_metrics`, and sets `instance` to the app's name rather than the proxy's address. Prometheus sends its scrape timeout along, and the agent stops the app's scrape at it. It scrapes the proxy's own metrics too. When the app stops, or its agent can't connect, the proxy no longer serves the path, and the app's job goes down: `up{job="my-app"} == 0` is the alert to set. `proxy_agent_map_size` counts the agents connected. See [Grafana & Alerting](https://prometheus-proxy.com/grafana/index.md) for dashboards and rules built on the proxy's metrics. --- Source: https://prometheus-proxy.com/production/ # Running in Production This page gathers what a production deployment of Prometheus Proxy needs from the security, reliability, and tuning settings documented elsewhere: first as a checklist, then section by section. ## Pre-Flight Checklist What to have in place before the proxy and its agents carry production scrapes, grouped as the sections below explain them. [`examples/proxy.conf`](https://prometheus-proxy.com/examples/index.md#production-proxy-proxyconf) and [`examples/agent.conf`](https://prometheus-proxy.com/examples/index.md#production-agent-agentconf) set the proxy's side of it and the agent's, to start from. **Security** - [ ] [TLS](https://prometheus-proxy.com/security/tls/index.md) (ideally mutual) enabled on the gRPC channel, and [confirmed on](https://prometheus-proxy.com/security/tls/index.md#confirm-its-on) - [ ] [Agent token](https://prometheus-proxy.com/security/index.md#agent-authentication-pre-shared-token) set ([per-agent identities](https://prometheus-proxy.com/security/index.md#per-agent-identities-and-path-authorization) where teams share a proxy), or mutual TLS in place - [ ] gRPC port reachable by agents; admin and dashboard ports **not** [publicly exposed](#security) **Running** - [ ] Proxy and agents run under a [supervisor](#running-as-a-service) that restarts them (systemd, Kubernetes, Docker's `--restart`, or `brew services`) - [ ] A plan for [upgrades](https://prometheus-proxy.com/upgrading/index.md): the proxy first, with a check before its restart and a way back - [ ] [Liveness probes](https://prometheus-proxy.com/kubernetes/index.md#health-probes-resources) on `/ping`; readiness on `/ping` (proxy) and `/healthcheck` (agent) - [ ] An embedded agent's [`stopTimeout`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo) inside the platform's shutdown window, and an [`onFailure`](https://prometheus-proxy.com/embedded-agent/index.md#starting-where-theres-a-proxy) handler where a failed start should be reported beyond the log **High Availability** - [ ] [Consolidated mode](https://prometheus-proxy.com/advanced/index.md#consolidated-mode) where you need agent redundancy, with each agent scraping a separate instance **Sizing & Tuning** - [ ] `maxConcurrentClients` / timeouts [tuned](#sizing-tuning) for your targets - [ ] [Content-size limits](https://prometheus-proxy.com/configuration/proxy/index.md#content-size-limits) sized for your largest payload - [ ] JVM heap [sized](#sizing-tuning) for peak decompressed payload × concurrency **Observability** - [ ] [Metrics enabled](https://prometheus-proxy.com/monitoring/index.md#enabling-metrics) and scraped by Prometheus - [ ] [Grafana dashboards imported](https://prometheus-proxy.com/grafana/index.md#importing) and [alert rules](https://prometheus-proxy.com/grafana/index.md#alerting-rules) loaded - [ ] [Admin endpoints](https://prometheus-proxy.com/monitoring/index.md#admin-endpoints) enabled on the proxy and agents, which the health probes need - [ ] The proxy's [dashboard](https://prometheus-proxy.com/web-dashboard/index.md) enabled, behind a [login](https://prometheus-proxy.com/web-dashboard/index.md#login) and on an [internal network](https://prometheus-proxy.com/dashboard-exposure/index.md#exposure), so finding why a scrape fails [never needs a restart](#observability) ## Security - **Encrypt the gRPC channel with TLS**, and prefer **mutual TLS** so the proxy authenticates agents and vice-versa. See [TLS Setup](https://prometheus-proxy.com/security/tls/index.md). - **Set an agent token** (`--agent_token` / `AGENT_TOKEN`) as a lightweight app-level control in addition to TLS. An empty token, with no per-agent identities or mutual TLS, leaves the agent port open and logs a startup warning. - **Prefer per-agent identities over one shared token.** A shared token cannot tell agents apart, so any holder can register any path, and silently take it over, including one already served by another agent. Named identities under `proxy.auth` scope each agent to its path patterns, and one can be revoked without touching the others, though adding or revoking one takes a proxy restart, which reconnects every agent. See [Per-Agent Identities](https://prometheus-proxy.com/security/index.md#per-agent-identities-and-path-authorization), including the incremental migration path from a shared token, and [Onboarding a Team](https://prometheus-proxy.com/onboarding/index.md), which adds an identity with a check before the restart and the way back. - **Segment the network** so only trusted agents can reach the gRPC port (`50051`). - **Keep the scrape port (`8080`) to Prometheus.** It has no authentication, and whoever reaches it can have the agents scrape their targets with any query string and `Authorization` header. Bind it to a private address with `proxy.http.host` and firewall it. See [Scrape Port Access](https://prometheus-proxy.com/security/index.md#scrape-port-access). - **Do not expose the admin or dashboard ports publicly.** `/threaddump` and the other admin endpoints are operational tools, not public endpoints, so keep ports `8092` and `8093` on an internal network. The [dashboard](https://prometheus-proxy.com/web-dashboard/index.md) port (`8094`) is unauthenticated too, until you set its [login](https://prometheus-proxy.com/web-dashboard/index.md#login) with `DASHBOARD_PASSWORD`, and shows agent names, hostnames, and target URLs. It runs on a separate port precisely so it can be firewalled without cutting off the `/ping` and `/healthcheck` probes. Bind it to a private address with `proxy.dashboard.host`, and set a login, with TLS in front of it, where more people can reach the port than should read it. - **Guard the dashboard against other sites.** If browsers that also load untrusted pages can reach it, set `proxy.dashboard.allowedHosts` to the names you use. Behind a reverse proxy, list its public origin in `proxy.dashboard.allowedOrigins` and its address in `proxy.dashboard.trustedProxies`, so each user behind it has a limit on wrong logins ([Client Addresses](https://prometheus-proxy.com/dashboard-exposure/index.md#client-addresses)). Unless a page of yours embeds the dashboard, set `proxy.dashboard.framingEnabled = false`, so no other site's page can frame it, and a security scan doesn't report the dashboard as missing an anti-clickjacking header; with `proxy.dashboard.screens` listed, the proxy's [screens page](https://prometheus-proxy.com/screens-page/index.md#screens) still frames it, from the dashboard's origin. Each screen that page lists must allow framing, and keeps its login, which works in a frame only on the same site; for one login across them, put single sign-on in front of them all. See [Exposure](https://prometheus-proxy.com/dashboard-exposure/index.md#exposure). - **Set the login before turning on relayed agent dashboards.** With `proxy.dashboard.agentScreens` on, the same login guards every connected agent's relayed dashboard. On a proxy several teams share, see [The Dashboard on a Shared Proxy](https://prometheus-proxy.com/security/index.md#the-dashboard-on-a-shared-proxy). - When forwarding auth headers to targets, **require TLS** so credentials aren't sent in plaintext between proxy and agent. See [Auth Header Forwarding](https://prometheus-proxy.com/security/index.md#auth-header-forwarding). ## Running as a Service In production, run the proxy and agents under a supervisor that starts them at boot and restarts them if they exit. `nohup` keeps a process running after you log out, but nothing restarts it, so don't rely on it here. A proxy that can't start, for example because one of its ports is already taken, logs the reason and exits with status 1, so the supervisor's restart policy retries it. Before 4.3.0 it logged the error but kept running, holding its admin and metrics ports, so no restart policy ever fired. See [The proxy or agent exits at startup](https://prometheus-proxy.com/troubleshooting/index.md#the-proxy-or-agent-exits-at-startup). - **Kubernetes** restarts a failed container and reschedules its pod. See [Kubernetes](https://prometheus-proxy.com/kubernetes/index.md). - **Docker** does it with `--restart unless-stopped`, or `restart: unless-stopped` in Compose. See [Running in the Background](https://prometheus-proxy.com/docker/index.md#running-in-the-background). - **Homebrew**'s `brew services start` runs it under launchd on macOS or systemd on Linux and starts it at login; `sudo brew services start` starts it at boot instead. See the [Quick Start](https://prometheus-proxy.com/getting-started/index.md). - **systemd**, for the JARs on a Linux host: a unit like this one for the proxy, installed as `/etc/systemd/system/prometheus-proxy.service`. It assumes the JAR is in `/opt/prometheus-proxy`, the config is in `/etc/prometheus-proxy`, and an unprivileged `prometheus` user exists (create it with `sudo useradd --system --no-create-home prometheus`): ```ini [Unit] Description=Prometheus Proxy Wants=network-online.target After=network-online.target [Service] User=prometheus ExecStart=/usr/bin/java -jar /opt/prometheus-proxy/prometheus-proxy.jar --config /etc/prometheus-proxy/proxy.conf Restart=on-failure RestartSec=5 # The JVM exits with 143 when systemd stops it with SIGTERM; count that as a clean stop. SuccessExitStatus=143 [Install] WantedBy=multi-user.target ``` For an agent, use `prometheus-agent.jar` and its config, `/etc/prometheus-agent/agent.conf`, and name the unit `prometheus-agent.service`. Start each config from its starter, [`examples/proxy.conf`](https://prometheus-proxy.com/examples/index.md#production-proxy-proxyconf) and [`examples/agent.conf`](https://prometheus-proxy.com/examples/index.md#production-agent-agentconf), each the settings the [Pre-Flight Checklist](#pre-flight-checklist) asks for, and edit it before you start its unit: the agent's needs its proxy and its endpoints. ```bash BASE=https://raw.githubusercontent.com/pambrose/prometheus-proxy/4.9.0/examples sudo mkdir -p /etc/prometheus-proxy /etc/prometheus-agent sudo curl -fL -o /etc/prometheus-proxy/proxy.conf "$BASE/proxy.conf" sudo curl -fL -o /etc/prometheus-agent/agent.conf "$BASE/agent.conf" ``` Then: ```bash sudo systemctl daemon-reload sudo systemctl enable --now prometheus-proxy # start now and at every boot systemctl status prometheus-proxy # check that it is running journalctl -u prometheus-proxy -f # follow its log sudo systemctl restart prometheus-proxy # pick up an edited config sudo systemctl disable --now prometheus-proxy # stop, and no longer start at boot ``` ## High Availability - For **proxy** redundancy, give the agent an ordered list of proxy endpoints. It uses the first that accepts it, and moves to the next on a failed connect or when a proxy rejects its registration (or every one of its static paths, for a cause that can't clear); when a registered connection drops it returns to the head of the list, so a recovered primary is picked up on the next reconnect without any manual step. ```hocon agent { proxy { endpoints = [ "proxy-a.example.com:50051", "proxy-b.example.com:50051" ] } } ``` Equivalently `--proxy proxy-a.example.com:50051,proxy-b.example.com:50051`, or the same comma-separated value in `PROXY_HOSTNAME`. Only one connection is active at a time; the agent registers its paths on whichever proxy it is connected to. Point Prometheus at **both** proxies with identical target lists, as [Scraping an HA Pair](#scraping-an-ha-pair) below describes: it has a requirement that is easy to get wrong. Failing over is quick: a refused connection, or a name that doesn't resolve, moves the agent to the next endpoint, which it tries within `agent.internal.reconnectPauseSecs` (3 seconds by default). Two things can slow a switch: - An endpoint whose host is gone, rather than refusing connections, isn't known to be down until the connection attempt times out. That takes `agent.grpc.unaryDeadlineSecs` (`--unary_deadline_secs`, 30 seconds by default), the deadline on every unary call, the connection's first among them. Lowering it shortens the wait, at the cost of patience with a slow proxy. - The JVM remembers a failed name lookup for 10 seconds (`networkaddress.cache.negative.ttl`, set in the JDK's `java.security`). Where a proxy's name stops resolving while it is down, as a stopped container's does on a Docker network, an agent that looked the primary up during the outage skips it for up to 10 seconds after it returns. If the agent's connection to the standby drops in that window, as when the standby is taken down moments after the primary comes back, it skips the primary, waits out the deadline above on the departed standby, and only then reaches the primary. Give a recovered primary a few seconds before stopping the standby. All endpoints share one TLS configuration. The agent builds one TLS context and one authority override for the whole list, so its trust collection must hold every proxy's CA, and an `overrideAuthority` must be a name every proxy's certificate carries; otherwise the handshake fails with an opaque error rather than a clear configuration error. - For **agent** redundancy, use [consolidated mode](https://prometheus-proxy.com/advanced/index.md#consolidated-mode), with each agent scraping a separate instance of the service: the proxy merges their answers into each scrape of the path, and keeps serving it, with the remaining agents' series, while one is down. Agents that scrape the same endpoint send every series once per agent, which Prometheus rejects as duplicates, logging an error on every scrape. A **rolling upgrade** needs no consolidated mode: an agent redeployed with the same identity takes its paths over when it registers. - For **health probes**, point Kubernetes liveness probes at `/ping`, and readiness probes at `/ping` on the proxy and `/healthcheck` on the agent. The proxy's `/healthcheck` measures load, so alert on it rather than take a busy proxy out of rotation. See [Kubernetes](https://prometheus-proxy.com/kubernetes/index.md#health-probes-resources). ### Scraping an HA Pair !!! warning "Use `static_config`, not `http_sd_config`" A standby proxy, one no agent is currently connected to, returns an **empty list** from its service-discovery endpoint. Under `http_sd_config` Prometheus treats that as "these targets no longer exist" and **deletes** them: no `up=0`, no failed scrape, no alert. The series simply stop, which is the one failure mode an HA pair is supposed to make impossible. With `static_config`, the standby returns `404` for a path it does not know, and Prometheus records `up=0` for that target, so losing the path on both proxies is a failed scrape you can alert on (below). ```yaml scrape_configs: - job_name: proxied-metrics static_configs: - targets: ["proxy-a.example.com:8080", "proxy-b.example.com:8080"] # One instance for the series, whichever proxy serves them; up keeps each proxy's own metric_relabel_configs: - target_label: instance replacement: proxied-metrics ``` Both proxies are scraped every interval. At any moment one of them has the agent connected and returns the metrics; the other returns `404` and shows as `up=0`, so an alert on each target's `up == 0` fires for the standby all the time. Alert on the job instead, which fires only when neither proxy serves the path: `max by (job) (up{job="proxied-metrics"}) == 0`. The series come from whichever proxy has the agent, so their `instance` label changes when the agent fails over. The `metric_relabel_configs` above give them one `instance` either way, so each series carries on across a failover, and leave `up`, which metric relabelling doesn't touch, with each proxy's. Or aggregate `without (instance)` in your queries. ## Sizing & Tuning Start from the defaults and adjust against the backlog and latency metrics: | Parameter | Default | When to change | |:----------------------------------------------|:--------|:--------------------------------------------------| | `agent.http.maxConcurrentClients` | 1 | Raise for many endpoints or slow targets | | `agent.scrapeTimeoutSecs` | 15 | Raise for slow targets | | `agent.http.clientTimeoutSecs` | 90 | Lower for fast-failing scrapes | | `agent.chunkContentSizeKbs` | 32 | Raise for large payloads to cut chunk count | | `agent.minGzipSizeBytes` | 512 | Lower to compress more aggressively | | `agent.http.maxContentLengthMBytes` | 10 | Raise for large scrape bodies (guards agent heap) | | `proxy.internal.maxZippedContentSizeMBytes` | 5 | Raise for large payloads sent in chunks | | `proxy.internal.maxUnzippedContentSizeMBytes` | 10 | Raise for large decompressed payloads | | `proxy.internal.maxAgentInactivitySecs` | 60 | Tune stale-agent eviction window | | `proxy.dashboard.agentScreensMaxMBytes` | 96 | Lower on a small heap (up to 1.6x it in heap) | Size the JVM heap for the largest **decompressed** payload times the scrape concurrency, and watch `agent_scrape_backlog_size` and `proxy_cumulative_agent_backlog_size`: a steadily growing backlog means agents can't keep up. See [Performance Tuning](https://prometheus-proxy.com/advanced/index.md#performance-tuning). ## Observability - **Enable metrics** on proxy and agent and scrape their internal `/metrics`. See [Monitoring](https://prometheus-proxy.com/monitoring/index.md#scraping-internal-metrics). - **Import the dashboards and alert rules** from [Grafana & Alerting](https://prometheus-proxy.com/grafana/index.md). - Alert on success rate, P99 latency, agent count, and backlog growth. `grafana/alerts.yml`, shown on that page, covers each. - **Enable the [operational dashboard](https://prometheus-proxy.com/web-dashboard/index.md)** (`--dashboard`) on an internal network, behind a [login](https://prometheus-proxy.com/web-dashboard/index.md#login). Grafana tells you *that* a target is failing; the dashboard shows *why*: which agent backs the path, whether that agent is still connected, and how its recent scrapes went, even for a path whose agent has already gone. [Troubleshooting](https://prometheus-proxy.com/troubleshooting/index.md#from-the-dashboard) starts from what it shows. - **Turn these on before you need them.** The proxy reads its metrics, admin, and dashboard settings only as it starts, so turning one on during an incident restarts the proxy, which interrupts every team's scrapes ([What a Proxy Restart Interrupts](https://prometheus-proxy.com/upgrading/index.md#what-a-proxy-restart-interrupts)). ## Logging - Leave `requestLoggingEnabled` on if you want a log line for each scrape. Those lines are at **DEBUG**, so they won't flood INFO on a busy proxy. - Use `logLevel = "trace"` for the most verbose output; the legacy `"all"` level was removed and now fails fast at startup. - gRPC's log lines come out through Logback with the rest, so a config named with `-Dlogback.configurationFile` sets their levels too, such as `` to quiet the INFO line and stack trace that a stray connection to the agent port logs. - To pick up edits to that file without a restart, set `scan="true"` on its `` element, as [`logback/docker-logback.xml`](https://github.com/pambrose/prometheus-proxy/blob/master/logback/docker-logback.xml) does; the config bundled in the JARs can't be watched. ## Shutdown - A standalone proxy or agent shuts down cleanly on SIGTERM. **Embedded** agents register no shutdown hook: stop one with `EmbeddedAgentInfo.shutdown()` where the application stops its services. The Ktor plugin and the Spring Boot starter do this with the app. See [Embedded Agent](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo). - `shutdown()` blocks until the agent has stopped, up to the builder's `stopTimeout`, or, without one, 30 seconds, after which it throws. Set `stopTimeout` inside the window the platform gives a process between SIGTERM and killing it, such as Cloud Run's 10 seconds, so the rest of the app's shutdown isn't left waiting on the agent: once it's up, `shutdown()` returns, with a warning, and the agent goes on stopping on its own. The Ktor plugin and the Spring Boot starter take it as their `stop-timeout`, 30 seconds by default. - The [Spring Boot Demo](https://prometheus-proxy.com/spring-boot-demo/index.md#a-graceful-shutdown) stops its agent before Tomcat's graceful shutdown begins, and the [Plain Kotlin Demo](https://prometheus-proxy.com/plain-kotlin-demo/index.md#scaling-in) finishes a worker's order on SIGTERM, then stops its agent. --- Source: https://prometheus-proxy.com/advanced/ # Advanced Topics ## nginx Reverse Proxy To use nginx as a reverse proxy in front of the gRPC service, disable the transport filter on both proxy and agent: ```text When using Nginx as a reverse proxy, disable the transport filter on both Proxy and Agent: java -jar prometheus-proxy.jar --tf_disabled java -jar prometheus-agent.jar --tf_disabled --config myconfig.conf Or via environment variable: TRANSPORT_FILTER_DISABLED=true Or via config: proxy.transportFilterDisabled = true agent.transportFilterDisabled = true ``` !!! warning "Disconnect detection" With `transportFilterDisabled`, the proxy can't see a connection close, only the agent's request stream end. An agent that disconnects ends that stream, and is removed at once. One that dies before opening its stream, or whose connection stays half-open, is removed after the inactivity timeout (default: 60 seconds, controlled by [`proxy.internal.maxAgentInactivitySecs`](https://prometheus-proxy.com/configuration/proxy/index.md#internal-settings)). In this mode the proxy also limits the agents connected as one auth identity, which is every agent when agent auth is off; see [Transport Filter](https://prometheus-proxy.com/configuration/proxy/index.md#transport-filter). !!! warning "nginx's request body limit" nginx counts everything an agent sends on a stream as one request body, and stops a body at `client_max_body_size`, 1 MB by default. An agent's streams of scrape results stay open for as long as it's connected, so behind nginx's default, every agent, of any version, is cut off each time its results add up to a megabyte: every few hours for results of a few hundred bytes every few seconds, every few minutes for results of tens of KB. It reconnects at once, and is briefly without its paths, which can fail a scrape. Turn the limit off in the `server` or `location` block that passes to the proxy, as [`nginx/docker/nginx.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/nginx/docker/nginx.conf) does: ```nginx client_max_body_size 0; ``` Without it, nginx's access log ends `writeResponsesToProxy` or `writeChunkedResponsesToProxy` with 413, its error log says `client intended to send too large chunked body`, and the agent logs `writeResponsesToProxy(): UNKNOWN HTTP status code 413`, then `Disconnected from proxy`. !!! warning "nginx's stream timeouts" An agent's connection ends when any of its streams closes, and nginx closes a stream that's quiet for 60 seconds by default. A stream can be quiet while the agent is scraped: the one it sends chunked results on carries nothing while its results stay under `chunkContentSizeKbs` (32 KB) gzipped. A current agent and proxy keep each of their streams open with a keepalive after 30 seconds of quiet, so nginx's default timeouts are enough for them. The proxy sets the interval for both directions, `proxy.internal.streamKeepAliveSecs`: keep it under the reverse proxy's idle timeout, or set it to 0 to turn keepalives off. Each side sends keepalives only once the other says it takes them, so with an agent or a proxy from 4.6.0 or earlier on either end, the agent is cut off every minute, scraped or not, reconnects, and is briefly without its paths, which can fail a scrape. For such a pair, raise both timeouts, in the `server` or `location` block that passes to the proxy: | Directive | Covers | |-----------|--------| | `grpc_read_timeout` | the streams the proxy sends on: scrape requests, and a current proxy's path notices | | `client_body_timeout` | the streams the agent sends scrape results on | Set them to a day or more, as [`nginx/docker/nginx.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/nginx/docker/nginx.conf) does: a stream for chunked results can stay quiet for as long as the results stay small, so a timeout above the scrape interval isn't enough, and even a day's cuts such an agent off once a day. Without them, nginx's access log ends the stream it closed with 408 (`client_body_timeout`) or 504 (`grpc_read_timeout`), and the agent's log shows `RST_STREAM closed stream` on `writeChunkedResponsesToProxy()` or `writeResponsesToProxy()`, or `HTTP status code 504` on `readRequestsFromProxy()` or `readPathNoticesFromProxy()`, then `Disconnected from proxy`, a minute after it connected. !!! warning "Reloads and connected agents" `nginx -s reload` starts new workers under the new config and leaves each open connection with the old worker it's on, under the old config, until the connection ends. An agent's connection, which the keepalives keep open, doesn't end, so a change a reload brings doesn't reach an agent connected before it, and each reload leaves old workers running. Set `worker_shutdown_timeout` in nginx's main context: ```nginx worker_shutdown_timeout 10s; ``` An old worker then closes its connections that long after a reload, and each agent reconnects at once, to a new worker, under the new config, at the cost of one reconnect per agent, which a scrape can land in. A worker takes the value from the config it started with, so it covers the reloads after it's in place: restart nginx once to bring it in. Example nginx and proxy configuration files are available in the repository: - [`nginx/docker/nginx.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/nginx/docker/nginx.conf) - [`nginx/nginx-proxy.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/nginx/nginx-proxy.conf) - The nginx Demo's configs, [`demos/nginx/nginx/`](https://github.com/pambrose/prometheus-proxy/tree/master/demos/nginx/nginx): `make up` in `demos/nginx` runs nginx with TLS and the dashboard on its stock timeouts, and `./demo.sh nginx-shutdown-timeout` adds `worker_shutdown_timeout` ### TLS at nginx To end the agents' TLS at nginx, serve TLS on its listener and pass the calls to the proxy's agent port in plaintext: ```nginx server { listen 443 ssl; # gRPC needs HTTP/2. http2 on; ssl_certificate /etc/nginx/certs/server.pem; ssl_certificate_key /etc/nginx/certs/server.key; location / { grpc_pass grpc://proxy-host:50051; } } ``` The proxy needs no TLS settings. The agent needs to know what to trust: set `agent.tls.trustCertCollectionFilePath` (or `trustCertCollectionPem`) to the CA certificate that signed nginx's. An agent uses TLS only when it has a trust collection or a client certificate, so set it even for a certificate a public CA signed, to a CA bundle. The agent checks nginx's certificate against the host it dials; `agent.tls.overrideAuthority` names another. The proxy warns at startup that agent tokens cross without TLS, as they do on the hop from nginx to the proxy, so keep that hop on a private network. To put the proxy's dashboard behind nginx too, see [Behind a reverse proxy](https://prometheus-proxy.com/dashboard-exposure/index.md#behind-a-reverse-proxy): its live updates need nginx to pass the WebSocket on. The [nginx Demo](https://prometheus-proxy.com/nginx-demo/index.md) runs all of this, and shows each of the warnings above. ## Prometheus Federation Scrape an existing Prometheus instance via the `/federate` endpoint: ```hocon agent { pathConfigs: [ { name: "Federated Prometheus" path: federated_metrics url: "http://prometheus-server:9090/federate?match[]={__name__=~\"job:.*\"}" } ] } ``` This leverages Prometheus's built-in federation support, allowing you to pull metrics from another Prometheus server through the proxy. A complete federation config, which also serves the agent's own metrics at `/agent_metrics`, in-process, is available at: [`examples/federate.conf`](https://github.com/pambrose/prometheus-proxy/blob/master/examples/federate.conf) ## Consolidated Mode By default, each scrape path is owned by a single agent. If a second agent tries to register the same path, it displaces the first agent, provided both connected with the same auth identity. With [per-agent identities](https://prometheus-proxy.com/security/index.md#per-agent-identities-and-path-authorization), another identity's registration is rejected while the first agent is connected. The displaced agent stays connected without the path, so two agents configured with the same path settle with the later one serving it. The proxy tells the displaced agent, whose [dashboard](https://prometheus-proxy.com/agent-dashboard/index.md) and log show the path as taken over, and the agent takes the path back once no agent serves it, as when a rolling deploy's new version stops, without reconnecting. While the other agent serves the path it only waits, through its reconnects too, so the two never take it from each other. Only a connection the agent itself has since replaced, one of the same launch, is disconnected when it loses its last path. To serve a path from both agents, make them consolidated. In **consolidated mode**, multiple agents can register the same path: ```hocon agent.consolidated = true ``` When a scrape request arrives for a consolidated path, the proxy sends it to every agent serving the path, waits for all of them, and merges their responses into one. If one agent disconnects, the remaining agents continue serving the path. Use cases: - **Several instances behind one path** — each agent scrapes a separate instance of a service, whose series carry a label that tells the instances apart, and Prometheus scrapes them as one target - **Redundancy** — the path keeps answering, with the remaining agents' series, while one agent is down - **Rolling upgrades** — new agent registers before old one deregisters !!! warning "Agents that scrape the same endpoint send each series twice" The proxy joins the agents' answers as they are, so when two consolidated agents scrape the same endpoint, Prometheus gets each of its series once per agent, with the same labels. It keeps the first sample of each and drops the others, logging `Error on ingesting samples with different value but same timestamp` for the target on every scrape and counting them in `prometheus_target_scrapes_sample_duplicate_timestamp_total`, while `up` stays 1. Give each consolidated agent a separate endpoint, and keep the agent Helm chart's `replicaCount` at 1, since its replicas all run the same config and scrape the same targets; Kubernetes replaces a failed agent pod. A rolling upgrade sends each series twice for as long as the old and new agents overlap. !!! note "A consolidated path belongs to one identity" With [per-agent identities](https://prometheus-proxy.com/security/index.md#per-agent-identities-and-path-authorization), a consolidated path records the identity that registered it, and only agents presenting that identity may join. Another identity's registration is rejected and retried, so it joins once the agents serving the path disconnect. Agents that share an identity — all of them, when agent auth is off -- can still join each other's consolidated paths, and a joining agent's output is merged into every scrape of the path, so one that never answers holds each scrape until it times out. ## gRPC Reflection [gRPC Reflection](https://grpc.io/docs/guides/reflection/) is disabled by default, because it lets anyone who reaches the agent port list and describe the proxy's API. Enable it with `proxy.reflectionDisabled = false` (or `-Dproxy.reflectionDisabled=false` on the command line) to let tools like [grpcurl](https://github.com/fullstorydev/grpcurl) inspect the service. When agent authentication is configured, reflection calls need a valid agent token, like every other call on the agent port: ```text # List available gRPC services: grpcurl -plaintext localhost:50051 list # Output: # ProxyService # grpc.reflection.v1.ServerReflection ``` ```text # Describe the ProxyService: grpcurl -plaintext localhost:50051 describe ProxyService # Note: If using TLS, omit the -plaintext flag and provide cert flags. # When the proxy requires agent tokens, present one: grpcurl -plaintext -H 'agent-token: ' localhost:50051 list ``` !!! note When using grpcurl with the `-plaintext` option, ensure the proxy is running without TLS. When TLS is enabled, provide the appropriate certificate flags. ## Performance Tuning ### Concurrent Scraping Increase the number of parallel scrapes for high-throughput scenarios: === "Config file" ```hocon agent { http { maxConcurrentClients = 10 // Parallel scrape limit clientTimeoutSecs = 30 // HTTP client timeout clientCache { maxSize = 200 // More cached clients maxAgeMins = 60 // Longer cache lifetime maxIdleMins = 20 // Longer idle tolerance cleanupIntervalMins = 10 // Less frequent cleanup } } chunkContentSizeKbs = 64 // Larger chunks for big payloads minGzipSizeBytes = 256 // Compress more aggressively scrapeTimeoutSecs = 30 // More time for slow targets } ``` === "Command line" ```bash # Increase concurrent scraping capacity: java -jar prometheus-agent.jar \ --max_concurrent_clients 10 \ --client_timeout_secs 30 \ --chunk 64 \ --config myconfig.conf # Tune HTTP client cache: java -jar prometheus-agent.jar \ --max_cache_size 200 \ --max_cache_age_mins 60 \ --max_cache_idle_mins 20 \ --config myconfig.conf ``` ### Key Tuning Parameters | Parameter | Default | Guidance | |:-----------------------|:--------|:--------------------------------------------------| | `maxConcurrentClients` | 1 | Increase for many endpoints or slow targets | | `clientTimeoutSecs` | 90 | Lower for fast-failing scrapes | | `chunkContentSizeKbs` | 32 | Increase for large payloads to reduce chunk count | | `minGzipSizeBytes` | 512 | Lower to compress more aggressively | | `scrapeTimeoutSecs` | 15 | Increase for slow targets | | `clientCache.maxSize` | 100 | Increase if many unique auth credentials are used | ## gRPC Keepalive Tuning Fine-tune gRPC keepalive behavior for specific network environments: ```hocon // Proxy gRPC keepalive settings: proxy.grpc { keepAliveTimeSecs = 7200 // Interval between PING frames keepAliveTimeoutSecs = 20 // Timeout for PING ack permitKeepAliveWithoutCalls = false permitKeepAliveTimeSecs = 300 // Min interval between client PINGs maxConnectionIdleSecs = -1 // -1 = unlimited maxConnectionAgeSecs = -1 // -1 = unlimited } // Agent gRPC keepalive settings: agent.grpc { keepAliveTimeSecs = -1 // -1 = gRPC's default, no keepalive PINGs keepAliveTimeoutSecs = 20 keepAliveWithoutCalls = false } ``` See the [gRPC keepalive guide](https://grpc.io/docs/guides/keepalive/) for detailed tuning advice. These settings send HTTP/2 PINGs, which check the connection but carry no data on a stream, so they don't keep a reverse proxy from closing a quiet stream: nginx answers a PING without resetting a stream's timeout. The agent and the proxy send keepalive messages on their streams for that, every `proxy.internal.streamKeepAliveSecs`; see [nginx Reverse Proxy](#nginx-reverse-proxy). ## Stale Agent Cleanup The proxy periodically checks for inactive agents and evicts them: ```hocon proxy.internal { staleAgentCheckEnabled = true maxAgentInactivitySecs = 60 // Evict after 60s of inactivity staleAgentCheckPauseSecs = 10 // Check every 10s scrapeRequestTimeoutSecs = 90 // Timeout for scrape requests } ``` !!! info When `transportFilterDisabled` is `true`, stale agent cleanup is automatically force-enabled, regardless of the `staleAgentCheckEnabled` setting. This ensures leaked agent contexts are eventually cleaned up. ## Zipkin Tracing Both proxy and agent support distributed tracing via Zipkin: ```hocon proxy.internal.zipkin { enabled = true hostname = "zipkin.example.com" port = 9411 path = "api/v2/spans" serviceName = "prometheus-proxy" sampleRate = 1.0 } agent.internal.zipkin { enabled = true hostname = "zipkin.example.com" port = 9411 path = "api/v2/spans" serviceName = "prometheus-agent" sampleRate = 1.0 } ``` Tracing covers each scrape and the gRPC calls between agent and proxy, each side reporting its spans under its `serviceName`. Spans are sent in the background, so a Zipkin server that can't be reached costs the spans, not the agent or the proxy. **A scrape's trace.** Each scrape Prometheus makes is a separate trace: | Span | Reported by | Covers | Tags | |:----------|:------------|:----------------------------------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------| | `scrape` | Proxy | Prometheus's request, until the proxy answers it | `path`, `agents`, `outcome` | | `forward` | Proxy | The request to one of the path's agents, until its result | `agentId`, `agentName`, `outcome`, `http.status_code`, `queue.wait_ms` | | `fetch` | Agent | The agent's request to the target | `path`, `http.url`, `outcome`, `http.status_code`, `gzipped`, `chunked`, `bytes.raw`, `bytes.filtered`, `filter.lines_dropped`, `retries` | A `scrape` span's remote endpoint is the address the request came from, which Zipkin shows as the span's client, so a trace says which Prometheus scraped. A path several agents serve has a `forward` span for each. A `forward` span's `queue.wait_ms` is how long, in milliseconds, the request waited in the agent's queue before the proxy sent it, and the span is annotated `sent to agent` once the agent's stream takes it. A scrape that ends first, as one that times out on an agent that has stopped reading can, has the wait but not the annotation. `outcome` is the scrape counters' label (see [Monitoring](https://prometheus-proxy.com/monitoring/index.md)), and a span whose scrape failed is tagged as an error, which Zipkin shows in red. `bytes.raw` and `bytes.filtered` are the payload's size before and after the path's [metric filter](https://prometheus-proxy.com/configuration/agent/index.md#metric-filtering), and `filter.lines_dropped`, on a path with a filter, the lines it dropped. `retries`, on a fetch the agent retried (`agent.scrapeMaxRetries`), is how many retries it made, whether or not the last one succeeded. The proxy sends the trace with each request, so the agent's `fetch` span joins it; an agent tracing scrapes for a proxy that doesn't begins a trace for each fetch. A scrape from a dashboard's Scrape now isn't traced. The proxy doesn't join trace headers a scrape request carries: its scrape port takes requests from anyone, and a client that marked its trace sampled could make the proxy keep every one. **The gRPC calls.** Zipkin joins the agent's client side and the proxy's server side of each call into one span, so a trace names both services. Connecting and registering are unary calls (`connectAgent`, `registerAgent`, and a `registerPath` for each path), each traced as it completes. `sendHeartBeat`, which an idle agent sends every few seconds, is never traced, and neither is `readPathNoticesFromProxy`, a stream that lasts the connection and tells the agent only when another agent takes one of its paths. Scrapes travel over long-lived streams (`readRequestsFromProxy`, `writeResponsesToProxy`, and `writeChunkedResponsesToProxy`), and a stream's span completes only when the stream ends, so it appears when its connection closes, lasting as long as it did; each scrape's trace shows the scrape. **Sampling.** `sampleRate` is the share of traces each side keeps: 1.0, the default, keeps every one, 0.1 one in ten, and 0 none. It takes 0, or from 0.01 to 1, and anything else fails startup. The proxy decides for each scrape, and the agent follows the decision the proxy sends, so a scrape's trace is kept whole or not at all. Each side's rate applies to its gRPC calls too: the agent's to the calls it makes, and the proxy's to the calls it serves, whatever trace headers a call carries, so no caller can have the proxy keep more of them than its rate, or trace a heartbeat. With different rates, Zipkin can show a call with one side's half only. Start Zipkin before the proxy and agents. Spans sent while it can't be reached are dropped: the reporter warns once, then logs further failures only at the `FINE` level, so after that first warning, lost spans leave nothing in the logs. --- Source: https://prometheus-proxy.com/operate/ # Operate For the team that runs the proxy once it's deployed, often for several teams at once: seeing what the proxy and its agents are doing, giving each team's agents a separate identity, upgrading, watching their metrics and alerts, and finding out why a scrape fails.
- [Dashboards](https://prometheus-proxy.com/dashboards/index.md) The proxy's dashboard and each agent's, the screens page that holds them in one browser tab, and what to do before anyone but the proxy host reaches them. - [Onboarding a Team](https://prometheus-proxy.com/onboarding/index.md) Give a team's agents a separate identity, scoped to the paths they may register, so one proxy serves every team. - [Upgrading](https://prometheus-proxy.com/upgrading/index.md) Moving the proxy and its agents to a new release: which versions work together, what to upgrade first, what a restart interrupts, and how to go back. - [Monitoring](https://prometheus-proxy.com/monitoring/index.md) The proxy's and the agents' metrics and admin endpoints: how to turn them on, and what each metric measures. - [Grafana & Alerting](https://prometheus-proxy.com/grafana/index.md) Ready-to-import Grafana dashboards and Prometheus alerting rules built on those metrics. - [Troubleshooting](https://prometheus-proxy.com/troubleshooting/index.md) Every status Prometheus can get from the proxy, and every way an agent can fail to connect or register, from what the dashboard or a `curl` shows to the fix.
--- Source: https://prometheus-proxy.com/dashboards/ # Dashboards The proxy and each agent can serve a dashboard, off by default, that shows what it's doing without anyone reading its logs. Anyone who can reach the proxy's dashboard can read it until you set a login, so read Exposing the Proxy Dashboard before anyone but the proxy host reaches it.
- [Proxy Dashboard](https://prometheus-proxy.com/web-dashboard/index.md) The proxy's view of its agents, their paths, and their recent scrapes, in four views: Agents, Paths, Activity, and Settings. - [Screens Page](https://prometheus-proxy.com/screens-page/index.md) The proxy's dashboard, direct and relayed agent dashboards, Prometheus, and Grafana in one browser tab: one at a time, two side by side, or all in a grid. - [Exposing the Proxy Dashboard](https://prometheus-proxy.com/dashboard-exposure/index.md) What the dashboard guards against on its own, a reverse proxy in front, which ports to firewall, and an HA pair. - [Agent Dashboard](https://prometheus-proxy.com/agent-dashboard/index.md) What the proxy's dashboard can't show: an agent's connection while it can't reach the proxy, each path the proxy refused and why, and each path's scrapes as the agent saw them.
--- Source: https://prometheus-proxy.com/web-dashboard/ # Proxy Dashboard The proxy's dashboard answers the question this system raises most often: **why isn't this target scraping?** Without it, that answer lives in the logs of two different machines, or in a JSON debug servlet. The proxy already holds everything needed to answer it: which agents are connected, which paths they serve, and how recent scrapes went. The dashboard shows it on one page, live.
![Nine rows of the Paths view, each a path, the agent serving it, and its last scrape's status, all 200: agent-east serves its path and the catalog, inventory, orders, payments, and proxy paths, agent-west-1 and agent-west-2 serve theirs, and shipping_metrics is served by agent-west-2 and one more agent](https://prometheus-proxy.com/images/demo/layout-paths-rows.webp)
The Path, Agent(s), and Status columns of the Paths view in the Basics Demo
To see it running, run `make up` in a clone's [`demos/basics`](https://github.com/pambrose/prometheus-proxy/tree/master/demos/basics): it starts the dashboard with three agents, a set of simulated services, Prometheus, and Grafana, all on one machine, and `make down` removes the demo. The [Basics Demo](https://prometheus-proxy.com/basics-demo/index.md) page walks through a failing target, paths discovered at runtime, and an evicted agent, with screenshots of each. Select any screenshot on either page to see the whole view full size. ## Four Views { #four-layouts } The tabs in the top bar switch between four views, each a URL you can bookmark or share. The Left and Right arrow keys open the view before or after the current one, except while you're typing in the search. | View | Answers | |---|---| | [**Agents**](#the-agents-layout)
`/dashboard` | "what is this agent doing?" | | [**Paths**](#the-paths-layout)
`/dashboard/paths` | "why isn't this target scraping?" | | [**Activity**](#the-activity-layout)
`/dashboard/activity` | "what just happened?" | | [**Settings**](#the-settings-layout)
`/dashboard/settings` | "how is this proxy set up?" | Start from **Paths** when Prometheus reports a target failing: that view is organized the way the alert is. Use **Agents** when you already know which agent you care about. Use **Activity** when an agent's paths never appeared, or the agent never did: what the proxy refused is in no other view, since nothing was added. Use **Settings** to check what the proxy is running with. This dashboard shows agents once they connect. For an agent that can't, or a path the proxy refused, turn on the agent's [dashboard](https://prometheus-proxy.com/agent-dashboard/index.md), which shows its connection and each path from the agent's side. The [screens page](https://prometheus-proxy.com/screens-page/index.md) holds this dashboard, direct agent dashboards, Prometheus, and Grafana in one browser tab, and can show [relayed agent dashboards](https://prometheus-proxy.com/screens-page/index.md#agent-screens), which come through the agents' connections, when the agents are behind a firewall. Every view shows times in your browser's time zone, as Grafana does, whatever zone the proxy runs in, so a failed scrape here and the spike it caused in a Grafana panel read the same clock. Hover over a time for its date and zone. ## Enabling It !!! warning "Off by default, and open until you set a password" The dashboard has **no TLS**, and **no authentication until you set a password** (`DASHBOARD_PASSWORD`; see [Login](#login)). It shows agent names, hostnames, target URLs, labels, recent activity, and the proxy's settings in one place, though never a token or password. Anyone who can reach it can also have the proxy scrape a path and read the start of what it returns. Treat its port as internal, and don't expose it publicly, with a login or without one. It listens on all interfaces by default, and without a login the proxy logs a warning at startup when it does. Set `proxy.dashboard.host` (or `--dashboard_host`) to `127.0.0.1` to keep it on the proxy host. Before anyone else reaches it, read [Exposing the Proxy Dashboard](https://prometheus-proxy.com/dashboard-exposure/index.md): who can reach it, putting it [behind a reverse proxy](https://prometheus-proxy.com/dashboard-exposure/index.md#behind-a-reverse-proxy), running it on an [HA pair](https://prometheus-proxy.com/dashboard-exposure/index.md#running-an-ha-pair), and its [limits](https://prometheus-proxy.com/dashboard-exposure/index.md#limits). === "Config file" ```hocon proxy { dashboard { enabled = true port = 8094 // Its own port, not the admin port path = "dashboard" // Served at http://:8094/dashboard host = "0.0.0.0" // "127.0.0.1" keeps it on the proxy host refreshIntervalSecs = 2 // How often drifting counters are re-pushed pathHistorySize = 20 // Scrapes kept per path, for History and each agent's Recent scrapes departedPathRetentionSecs = 3600 // How long a path whose agent has gone stays listed activityLogSize = 500 // Lines kept in the Activity view scrapeNowEnabled = true // A Scrape button on each path; false removes it and its route links = [] // Links from each path into other tools; see Links below username = "admin" // The login's username, once a password is set password = "" // Requires a login; better set as DASHBOARD_PASSWORD, see Login below } } ``` === "Command line" ```bash java -jar prometheus-proxy.jar --dashboard --dashboard_port 8094 ``` === "Environment" ```bash DASHBOARD_ENABLED=true DASHBOARD_PORT=8094 java -jar prometheus-proxy.jar ``` Then open `http://:8094/dashboard`. The proxy reads these settings only as it starts, so turning the dashboard on restarts the proxy, which interrupts every team's scrapes ([What a Proxy Restart Interrupts](https://prometheus-proxy.com/upgrading/index.md#what-a-proxy-restart-interrupts)). Turn it on before you need it, rather than during an incident. ## Login Set a password, and the dashboard asks for a login before it shows anything: a browser gets its login page, and after a right login, the page it asked for. The username is `admin` unless you set another.
![The dashboard's login page](https://prometheus-proxy.com/images/demo/login.webp)
The login page, once a password is set
=== "Config file" ```hocon proxy { dashboard { enabled = true username = "ops" // admin unless set; DASHBOARD_USERNAME password = ${?OPS_PASSWORD} // From the environment, so the file holds no password } } ``` === "Environment" ```bash DASHBOARD_ENABLED=true DASHBOARD_PASSWORD='' java -jar prometheus-proxy.jar ``` The username and password have no command-line flags, since a command line shows in `ps`. Set the password from the environment, or from a Secret on a platform that has them, rather than in a config file others can read. A login in a browser starts a session, which ends after 24 hours without a request, 7 days after the login, or with **Log out**, the exit icon at the end of the top bar. A script sends the login with each request as HTTP Basic Auth instead, and needs no session: ```bash curl -u admin:'' http://proxy-host:8094/dashboard/paths ``` ??? info "How sessions, the cookie, and Basic Auth work" The browser keeps its session in a cookie. The proxy keeps sessions in memory, so a restart signs everyone out. A page left open when its session ends goes to the login page by itself: at once after Log out in another tab, within one refresh interval (`proxy.dashboard.refreshIntervalSecs`, 2 seconds by default) after the session expires, and once the proxy is back after a restart. The cookie is: - `HttpOnly` and `SameSite=Lax`; - named for the dashboard's port, so two proxies on one host keep separate sessions; - set at the dashboard's path, and at `/screens` too while the proxy serves the [screens page](https://prometheus-proxy.com/screens-page/index.md#screens); - `Secure` when the browser reached the dashboard over `https`, as through a reverse proxy. Signing in from a link into the screens page returns to it, with the screen and view the link named. Signing in with no page to return to, as from the login page Log out leaves a browser on, goes where the dashboard port's root does: the screens page while the proxy serves one, else the dashboard. A browser already signed in, as from another tab, that opens the login page goes straight on to the page it was for. With a login set, the dashboard tells the browser to keep none of its pages (`Cache-Control: no-store`), so a page behind the login isn't kept to be shown again after Log out. A browser can't use Basic Auth: it always gets the login page, even with a Basic login it saved for the dashboard's address earlier, so Log out signs it out. The dashboard tells a browser by the headers a script doesn't send: a page navigation's `Accept: text/html` or `Upgrade-Insecure-Requests`, an `Origin` or a `Referer`, or `Sec-Fetch-Mode`, which a browser sends only over `https` or to `localhost`. So a script that sends one of those gets the login page, or a 401, as a browser does. After 10 wrong logins from one address within a minute, or 100 from all of them together, the dashboard refuses every login from that address, or from any, with a 429, the right password included. It refuses them until the oldest of those wrong logins is a minute old, so a guesser can't try passwords in parallel. Behind a reverse proxy, every login comes from the proxy's address, so the first limit is everyone's, and during an attack the real users wait out the minute too. List the reverse proxy in `proxy.dashboard.trustedProxies` to fix that; see [Client Addresses](https://prometheus-proxy.com/dashboard-exposure/index.md#client-addresses). The proxy logs the username and that a password is set, never the password. It logs a wrong login at WARN, with the [client's address](https://prometheus-proxy.com/dashboard-exposure/index.md#client-addresses), at most once a minute for each address, and logs reaching the limit. It refuses to start with an empty username, a colon in it (where Basic Auth splits the username from the password), or a control character in either, such as the trailing newline of a password read from a file. !!! warning "Put TLS in front of it" The dashboard serves plain HTTP, so the password, and the session cookie after it, cross the network readable by anyone who can watch the traffic. Off the proxy host, reach the dashboard through a reverse proxy that terminates TLS (list its public origin in `allowedOrigins`; see [Exposure](https://prometheus-proxy.com/dashboard-exposure/index.md#exposure)), an SSH tunnel, or `kubectl port-forward`. A login doesn't make the port safe to expose publicly. ## The Status Bar The bar across the top appears in every view. It starts with the logo and which proxy the page is: its host's name and the port Prometheus scrapes, as `Proxy: proxy:8080`, so the dashboards of several proxies are told apart at a glance. After the tabs it shows the connection's **live** indicator, the current **agents** and **paths** counts, how many paths are **failing** (their last scrape failed) or **departed** (their agent has gone) when there are any, and two health gauges, **chunks** and **scrapes**. The browser tab's title names the proxy the same way and counts the failing and departed paths too, as `(3 problems) Proxy: proxy:8080`, so a dashboard left in a background tab still says when something is wrong. At the bar's end, the theme button shows the theme in force, **light** (the sun), **dark** (the moon), or **auto** (the half-filled circle), the default, which follows your system's light or dark setting. Each click moves to the next theme, in that order, and its tooltip names the theme in force and the next. The browser remembers the choice for that dashboard, and its login page uses it too. The dashboard's other open pages follow a change at once, the [screens page](https://prometheus-proxy.com/screens-page/index.md#screens) and the dashboard in its frame included. ### The Live Indicator The **live** indicator is the connection's status, not the proxy's. If the proxy restarts or the connection drops, the green dot turns red and reads **reconnecting…**; the browser retries roughly every two seconds and the dot returns to green on its own once it reconnects — no reload. A page that still says *live* is genuinely receiving updates, so a frozen dashboard cannot masquerade as a healthy one. A tab in the background gives up its connection and reconnects as soon as you return to it. That is a pause, not an outage, so it doesn't turn the dot red, and tabs left open in the background don't count against `proxy.dashboard.maxSessions`. The retry interval is deliberately short and fixed. htmx's default WebSocket backoff doubles after each failed attempt, up to a minute, which for an internal dashboard means the page can stay dark for tens of seconds after the proxy is already back. A steady two-second retry recovers within about that long of the proxy returning, at the cost of retry traffic that is negligible on a LAN. ### `chunks` and `scrapes` `chunks` and `scrapes` are **transient in-flight gauges**, not running totals — they count work happening *right now*, so at rest they sit at `0`. The number after the slash is a health threshold, not a capacity. - **scrapes `N`/800** — scrape requests currently being serviced. The proxy adds one for each agent it sends a scrape to, a [Scrape now](#scrape-now) included, and removes it the moment the agent responds, times out, or disconnects. It rises with concurrent in-flight scrapes — many paths at once, a slow endpoint, or a high scrape rate — and falls back to `0` as they drain. - **chunks `N`/800** — large responses currently being reassembled. A response is streamed in chunks only when its gzipped body reaches `agent.chunkContentSizeKbs` (default 32 KB); the proxy holds one context per such response until its final chunk arrives. Small metrics payloads never touch it, so it stays `0` unless a big endpoint is mid-transfer. Two things keep them near `0` in practice. Each entry is removed as soon as its request completes, and the bar re-samples them on the refresh timer (`proxy.dashboard.refreshIntervalSecs`, ~2 s) rather than on every scrape, so a fast scrape opens and closes well inside that window. To watch them move, point an agent at an endpoint whose body gzips to 32 KB or more, usually several hundred KB of text (chunks), or drive concurrent or slow scrapes (scrapes), ideally with a shorter `refreshIntervalSecs`. The `/800` is the **unhealthy threshold** (`proxy.internal.scrapeRequestMapUnhealthySize` and `chunkContextMapUnhealthySize`, by default 80% of `maxInFlightScrapeRequests`). When either count reaches it, both turn amber — a backpressure signal that requests are not draining: agents stuck or slow, or a leak. Green and near `0` is the healthy resting state. ## The Agents View { #the-agents-layout }
![The Agents view in the Basics Demo, with agent-east selected](https://prometheus-proxy.com/images/demo/layout-agents.webp)
The Agents view in the Basics Demo, with agent-east selected
Agents are listed on the left. Selecting one shows, on the right: | Panel | What it shows | |---|---| | **Identity** | agent name, remote address, host name, the [auth identity](https://prometheus-proxy.com/security/index.md) it connected as, launch ID, consolidated flag | | **Liveness** | uptime, idle time, scrape backlog depth, and, while the [stale-agent check](https://prometheus-proxy.com/configuration/proxy/index.md#internal-settings) runs, seconds until it evicts the agent | | **Paths** | every path this agent has registered, and whether a path is shared with other agents | | **Recent scrapes** | this agent's latest 25 scrapes across its paths, newest first, with status, duration and payload size | An agent's recent scrapes come from each path's history, the one behind the [History](#the-paths-layout) column, so other agents' busy paths can't push them out. A path several agents share keeps all of their scrapes, and each agent's panel lists only that agent's. The remote address is the `host:port` the agent's connection came from, without a reverse DNS lookup. With the transport filter disabled, as behind an nginx reverse proxy, it reads `Unknown`: the connection there comes from the reverse proxy, not the agent. Before 4.3.0 it read `Unknown` for every agent. Selection lives in the URL, so one agent's panel is a link you can bookmark or share. The page updates **live over a WebSocket** — an agent connecting, disconnecting, or registering a path appears without a refresh. If the agent you are looking at disconnects, the panel says so explicitly, naming the agent as the other views do, rather than silently freezing on stale data. (The top-bar **live** indicator that reflects the connection itself is described under [The status bar](#the-status-bar).) ## The Paths View { #the-paths-layout } Every path on one row, as in the [screenshot at the top of this page](#proxy-dashboard), with the endpoint behind it and how its last scrape went: | Column | What it shows | |---|---| | **Path** | the registered path Prometheus scrapes, with a button beside it that copies its URL on the proxy, the one to curl, built from the address you opened the dashboard at and the proxy's scrape port, and one that [scrapes it now](#scrape-now) | | **Agent(s)** | the agent serving it; a consolidated path shows the first plus a `+N` count | | **Identity** | with [agent authentication](https://prometheus-proxy.com/security/index.md) on, the identity that registered the path, which any other agent joining it must share; the legacy shared `agentToken` reads *shared token* | | **Target** | the URL the agent actually fetches, with a button beside it that copies it to the clipboard | | **Src** | `cfg` for a statically configured path, `disc` for one from [dynamic discovery](https://prometheus-proxy.com/configuration/agent/index.md#dynamic-target-discovery) | | **Last scrape / Status / Duration** | the most recent result for that path | | **History** | the path's recent scrapes as a row of dots, oldest on the left, green for a success and red for a failure, with faint dots holding the places of scrapes still to come, then the share that succeeded | | **Links** | with [links](#links) configured, the path's links into other tools, such as Prometheus and Grafana, by name or by the tool's icon | The dashboard explains the columns too: **Column guide**, at the right end of the search bar, opens a short explanation of each under the bar, which stays open as the table updates. Status says how the last scrape went; History says whether that is news. A target that fails every scrape and one that failed once in twenty look the same in Status alone. Each path keeps its last `pathHistorySize` scrapes (default 20) whatever the other paths are doing, and the percentage is rounded down, so a path with any failure never reads 100%. The copy button copies the URL as the table shows it. The agent [redacts](https://prometheus-proxy.com/security/index.md#credentials-in-urls) a target URL's user info and query values before sending it to the proxy, so a URL that carries either is copied with `***` in their place. ### What a Failing Row Means Status gives the HTTP status of the path's last scrape. Each red status, a `gone` agent, and a path with no row has a Troubleshooting section that says why, and what to do: | The row shows | What it means | See | |---|---|---| | 404 | The target answered 404: the target URL names a page it doesn't serve | [404 Not Found](https://prometheus-proxy.com/troubleshooting/index.md#404-not-found) | | 503 | The agent couldn't reach the target, left, was too busy, or didn't answer in time | [503 Service Unavailable](https://prometheus-proxy.com/troubleshooting/index.md#503-service-unavailable) | | 502 | The target answered 502, or the proxy couldn't use the agent's answer | [502 Bad Gateway](https://prometheus-proxy.com/troubleshooting/index.md#502-bad-gateway) | | 413 | The body passed the agent's or the proxy's size limit | [413 Payload Too Large](https://prometheus-proxy.com/troubleshooting/index.md#413-payload-too-large) | | 408 or 504 | The target was too slow for the agent's scrape timeout, or answered so itself | [408 Request Timeout and Other Timeouts](https://prometheus-proxy.com/troubleshooting/index.md#scrape-hangs-then-times-out) | | 499 | Prometheus hung up at its `scrape_timeout`, before the agent answered | [408 Request Timeout and Other Timeouts](https://prometheus-proxy.com/troubleshooting/index.md#scrape-hangs-then-times-out) | | Another red status | The target's answer, passed through | [Prometheus Scrape Returns an Error](https://prometheus-proxy.com/troubleshooting/index.md#prometheus-scrape-returns-an-error) | | `gone` | The path's agent left, and Prometheus gets a 404 for the path | [Agent Can't Connect to the Proxy](https://prometheus-proxy.com/troubleshooting/index.md#agent-cant-connect-to-the-proxy) | | No row | No agent registered the path; a refusal shows in the [Activity](#the-activity-layout) view | [404 Not Found](https://prometheus-proxy.com/troubleshooting/index.md#404-not-found) | ### Searching and Filtering A search box above the table keeps only the rows whose path, agent, target URL or identity contains what you type, as the row shows it, ignoring case, so `team-a` shows one team's paths, and `/payments_metrics`, copied from Prometheus, finds that path. **Problems only** keeps the paths whose last scrape failed or whose agent has gone. Both apply as you type, and while either is on, the table says how many of the paths it is showing. The search goes into the page's URL, as `/dashboard/paths?q=team-a&problems=1`, so a filtered view is a link you can bookmark or send. Pressing Enter in the box does the same as typing, and the form works as a plain link without the page's script. ### Scrape Now The button after a path's copy button scrapes it at once, through its agent, exactly as Prometheus would. The result shows above the table: the status, how long it took, the size, the content type, how many metric families and samples came back, and the first 2 KB of the body. Only a body in the Prometheus text or OpenMetrics format is counted, so a protobuf one shows no families or samples. A failed scrape shows the agent's reason instead. A consolidated path is scraped from every agent and merged, as Prometheus sees it. Use it to check a fix without waiting for Prometheus's next scrape, or for a curl from a machine that can reach the scrape port. A scrape from the dashboard isn't one of Prometheus's, so it leaves no trace in what the proxy reports: not in the `proxy_scrape_*` metrics, the path's History, or the agent's recent scrapes. The [Activity](#the-activity-layout) view records it instead, with the [address](https://prometheus-proxy.com/dashboard-exposure/index.md#client-addresses) of the browser that asked. The proxy tells the agent the scrape came from the dashboard, so the agent counts it in `agent_dashboard_scrapes_total` rather than its `agent_scrape_*` counters and latency histogram. An agent older than this feature can't tell, and counts it as one of Prometheus's. The target sees it as any other scrape. So clicks can't crowd out Prometheus, at most four dashboard scrapes run at once, a path is scraped from the dashboard at most once every five seconds, and each waits at most ten seconds for its target. Past either limit the panel says why instead. `proxy.dashboard.scrapeNowEnabled = false` removes the button and its route. ### Links Each row can carry links that open its path in other tools: a Prometheus query, a Grafana dashboard, a runbook, a log search. Write each as a URL template in `proxy.dashboard.links`, and each row fills in its path's values. With any link configured, the table ends with a **Links** column naming each row's links, or showing their tools' icons; each opens in a new tab, or, on the [screens page](https://prometheus-proxy.com/screens-page/index.md#listing-screens), in its tool's tab there, beside the dashboard, when the page lists the tool. ```hocon proxy { dashboard { links = [ { name = "Prometheus" url = "http://prometheus:9090/query?g0.expr=up%7Bjob%3D%22{label.job}%22%7D" icon = "prometheus" } { name = "Grafana", url = "http://grafana:3000/d/proxy-targets?var-job={label.job}", icon = "grafana" } { name = "Runbook", url = "https://runbooks.example.com/proxy/{path}" } ] } } ``` Being a list, `proxy.dashboard.links` must be set in a config file rather than with `-D`. A link with an `icon` shows its tool's icon, in the tool's color, in place of its name. Hovering over the icon shows a tooltip such as *Open in Grafana*, and a screen reader says the name. The dashboard has two, `prometheus` and `grafana`, matched ignoring case; leave `icon` out, or empty, to show the name. The proxy serves the icons itself, so the dashboard still needs no access to the internet. The icons are from [Simple Icons](https://simpleicons.org) (CC0); the marks belong to their owners. A template can use: | Placeholder | Filled with | |---|---| | `{path}` | the path, without its leading slash | | `{agent}` | the name of the agent serving the path, as the Agent(s) column shows it | | `{identity}` | the path's [auth identity](https://prometheus-proxy.com/security/index.md); there is none with agent auth off or with the legacy shared `agentToken` | | `{label.}` | the value of the label `` the agent registered the path with, such as `{label.job}` | The proxy can't build a Prometheus link on its own. Service discovery gives every path the same target, the proxy's scrape address, and Prometheus drops `__metrics_path__` once relabeling is done. So what tells one path's series from another's is up to your deployment. It's usually a label the agent registers the path with, such as a separate job, which is what `{label.job}` reads. To identify series by path instead, keep the path as a label when Prometheus relabels the proxy's targets: ```yaml scrape_configs: - job_name: prometheus-proxy http_sd_configs: - url: http://proxy:8080/discovery relabel_configs: - source_labels: [__metrics_path__] target_label: path ``` The label holds the path with its leading slash, after any path prefix in `proxy.service.discovery.targetPrefix`, so with no prefix a link can query `up{path="/{path}"}`, written into the URL as `http://prometheus:9090/query?g0.expr=up%7Bpath%3D%22%2F{path}%22%7D`. - **A missing value drops the link.** A row whose path lacks a value a template needs, such as a label it didn't register, gets no link for that template, never one with an empty slot. A row left with no link shows a dash. - **Paths whose agent has gone** keep no labels, so they keep only the links that use no `{label.…}`. They keep their identity, so an `{identity}` link still works on them. - **Values are encoded.** Each value is percent-encoded as a URL component, so a label can't add a path, query, or fragment, and a slash in a path becomes `%2F`. Write the rest of the template already encoded: PromQL's braces and quotes as `%7B`, `%7D`, and `%22`, as above. A label reads as the agent registered it, including one [service discovery](https://prometheus-proxy.com/service-discovery/index.md#labels) keeps out, such as a job with `reserveJobAndInstanceLabels` on. - **Checked at startup.** A link needs a name and an absolute `http` or `https` URL, and may use only the placeholders above, and only after the URL's host, so a label can't choose the site a link opens. A brace that isn't part of a placeholder fails too, as does an `icon` the dashboard doesn't have. Any of these stops the proxy at startup with a message naming the link. ### Paths Whose Agent Has Gone A path whose agent disconnected **stays on this screen**, marked `gone`, still naming the agent that was serving it, the identity it was registered as, and the target URL that agent scraped, with its copy button. This is the view's main reason to exist. The proxy deletes a path the moment its last agent departs, so the Agents view cannot show it — a target that *stopped* working simply disappears from that view, at exactly the moment you are looking for it. The Paths view keeps those rows from what the proxy recorded as each path left, and from its scrape history, both of which outlive the agent. A path whose agent left before Prometheus ever scraped it still gets its row, with an en dash for its scrape columns. Otherwise the row keeps its History column, so you can see whether the target was failing before its agent went. The search finds a gone path by its identity as it does a live one, so `?q=team-a` shows a team's gone paths too. A gone path stays for `departedPathRetentionSecs` (default 3600, an hour) after it was last seen: when its agent left, or its last scrape, if that came later. That is measured in time, not in scrapes, so a busy proxy keeps a gone path as long as a quiet one does. Earlier versions rebuilt these rows from the 200 most recent scrapes across all paths, which on a proxy with a hundred paths scraped every 15 seconds is about 30 seconds of history. At most 1,000 gone paths are kept, the one seen least recently dropped first, and none survives a proxy restart. It is a recent-past view, not an audit log. ## The Activity View { #the-activity-layout }
![The Activity view in the Basics Demo, searched for one agent, with a path the proxy refused](https://prometheus-proxy.com/images/demo/layout-activity.webp)
The Activity view in the Basics Demo, searched for one agent, with a path the proxy refused
What the proxy did with its agents and their paths, newest first: | Event | When | |---|---| | `connected` | an agent registered, with the address it connected from and its host name | | `disconnected` | an agent's connection closed or its stream ended, with how many paths it served | | `evicted` | the proxy removed an agent it hadn't heard from within [`proxy.internal.maxAgentInactivitySecs`](https://prometheus-proxy.com/configuration/proxy/index.md#internal-settings) | | `registered` / `unregistered` | an agent added a path, or removed one; re-registering a path it already serves isn't news | | `taken over` | an agent took a path another agent of the same identity was serving, as a redeploy does | | `scraped now` | a browser scraped a path with [Scrape now](#scrape-now), with the result and the browser's address | | `rejected` | the proxy refused a path, with its reason: one its identity may not register, a malformed or overlong path, a path another identity holds, a consolidated agent and a path that isn't (or the reverse), one with more than `maxLabelsPerPath` labels, or one past the agent's `maxPathsPerAgent` or its identity's `maxPathsPerIdentity` | | `refused` | an identity was already at `proxy.internal.maxAgentsPerIdentity`, so a connect was turned away | | `bad token` | a call came with no agent token or an unknown one, naming the host it came from | The last three, and `evicted`, are what **Problems only** keeps, marked in red; a take-over is marked in amber. Troubleshooting's [From the Dashboard](https://prometheus-proxy.com/troubleshooting/index.md#from-the-dashboard) leads from each of them to the section that explains it. The search works as on the Paths view, matching the event, agent, identity, paths, and detail, and goes into the URL the same way, and **Column guide** explains this table's columns as it does the Paths table's. A burst of like events from one agent within five seconds is one row, counted (`registered ×40`) and naming its first three paths. So an agent registering two thousand paths takes one row rather than the whole feed. A path the burst repeats, such as Scrape now clicked again on one path, is named and counted once. A rejection appears the first time the agent is told it, not on each retry. Bad tokens from one host within a minute are counted on one row. At most ten hosts a minute each get a row, and the rest of that minute's are counted on one, so a flood from many addresses can't push everything else out of the feed. A connect or a path change appears at once; a refusal or a bad token, which changes nothing else on the page, by the next refresh. The table is sent to your page again only when the feed has changed, or your search has, so a row you are reading or selecting isn't replaced on every refresh. The feed keeps the last `activityLogSize` rows (default 500), in memory only, so a restart empties it. It is a view of the recent past, for finding out why something didn't appear, not an audit log; the proxy's log has every event. ## The Settings View { #the-settings-layout }
![The Settings view in the Basics Demo](https://prometheus-proxy.com/images/demo/layout-settings.webp)
The Settings view in the Basics Demo
Every setting the proxy resolved from its flags, environment variables, config file, and defaults, so you can check what it runs with without reading its startup log: | Group | What it shows | |---|---| | About | the version, launch ID, when the proxy started, where its config came from, and the keys of any `-D` overrides | | Listeners | the scrape address, its idle timeout and request logging, the agent port, and blitz | | Agent authentication | off, a shared token, or how many identities; each identity's name and the path globs it may register; reflection; and the transport filter | | TLS | plaintext, TLS, or mutual TLS, and where each certificate and key comes from | | Scrapes | the scrape timeout, how many scrapes may be in flight, and the sizes and thresholds that turn the healthcheck unhealthy | | Agent limits | the stale-agent check, and the limits on what one agent, or one identity's agents, may register and report | | gRPC server | handshake, keepalive, and connection age settings, with gRPC's default named where one is left unset | | Service discovery | the endpoint's path and target, and whether agents' `job` and `instance` labels are kept | | Dashboard | where it listens, its login's username, its limits, what it keeps, its links, and its screens | | Admin, Metrics, Tracing, Logging | each service's port and paths, the JVM metrics turned on, Zipkin, and the log level | No secret reaches the page. The agent token, each identity's token, the dashboard's password, and TLS material given as PEM show only as set or not set, and a `-D` override shows only its key, never its value. File paths, identity names, their globs, and the login's username are shown: they are what you check when an agent is refused or a scrape fails. A warning the proxy logs at startup shows here too: an agent port any reachable peer can register on, or agent tokens sent without TLS. The settings don't change while the proxy runs, so the page is sent them once when it opens, and a value you select stays selected. If the proxy restarts, the page reconnects and shows the new process's settings. ## Accessibility Text clears WCAG AA's contrast ratio of 4.5:1, with 4.59:1 the lowest measured, and non-text indicators clear 3:1. The path table marks its headers, and a screen reader is told when the page loses its connection and gets it back, which the page never shows by color alone. --- Source: https://prometheus-proxy.com/screens-page/ # Screens Page { #screens } An operator works across several screens: the proxy's dashboard, each agent's dashboard, Prometheus, Grafana, and other tools. The screens page holds them all in one browser tab, at `/screens` on the [proxy dashboard](https://prometheus-proxy.com/web-dashboard/index.md)'s port, for example `http://proxy-host:8094/screens`. This page is for whoever sets the proxy up for a team: how to list the screens, link into the page, and show relayed agent dashboards, which come through the agents' connections, when the agents are behind a firewall. ## Listing Screens List the screens in `proxy.dashboard.screens`. It's a list, so set it in a config file: ```hocon proxy.dashboard.screens = [ { name = "agent-east", url = "http://agent-east.corp.example.com:8095/dashboard" } { name = "Prometheus", url = "http://prometheus.corp.example.com:9090", start = "/alerts", probe = "/-/healthy" } { name = "Grafana", url = ${?GRAFANA_URL}, start = "/d/overview?kiosk" } ] ``` Each screen has a `name`, which titles its tab, a `url`, its address, an optional `start`, the path it opens on, appended to `url`, and an optional `probe`, the path the page checks it answers at, appended to `url` too ([below](#tabs-and-layouts)). A proxy dashboard [link](https://prometheus-proxy.com/web-dashboard/index.md#links) into a listed tool opens in that tool's tab, beside the proxy's dashboard in Split, rather than in a new browser tab. With Grafana listed as above, a Paths row's Grafana link opens the row's dashboard in the Grafana tab. A link opens there when its `url` starts with the screen's `url` and continues with a `/`, a `?`, or nothing. Ctrl-click or Cmd-click still opens a new tab, as does a link into a tool the page doesn't list. The dashboard's top bar links to the page, and the port's root, `http://proxy-host:8094/`, leads to it. When no screens are listed and [relayed agent dashboards](#agent-screens) are off, the root leads to the proxy dashboard instead. The root needs no login: it only redirects, and the page asks for one. ## Tabs and Layouts The proxy's dashboard always has the first tab, and each listed screen has a tab after it. A tab's dot is green while its screen answers and red while it doesn't. The page checks every 5 seconds while it's visible, with a `HEAD` of the screen's `url`, or of its `probe` when it has one (of `/session` for the proxy's tab). The proxy's dashboard and a direct agent dashboard answer it with a 204 before any login, since it says only that they're up. Any answer counts, but the browser logs one that isn't a success or a redirect as an error, each time: give a tool that refuses a `HEAD` of its `url` a `probe` it answers, such as Prometheus's `/-/healthy`, since Prometheus answers a `HEAD` of its pages with a 405. A pane whose screen isn't answering says so, then reloads by itself once it answers again. | Layout | Shows | |---|---| | **One** | the selected screen at full size | | **Split** | two screens side by side, each laid out to fit its pane; shift-click a tab to put its screen on the right | | **All** | every screen in a grid, each laid out at 1280×800 and scaled to its tile; click a tile's title to open it | Switching tabs or layouts never reloads a screen, so a dashboard keeps the agent or path you selected. Each pane's **Open in a tab** opens its screen on its own. In **All**, the grid scrolls, and each screen loads once its tile comes within half a screen of the view, so the tiles around the one you scroll to are ready.
![The screens page in Split, the proxy's failing paths beside Grafana](https://prometheus-proxy.com/images/demo/screens.webp)
The screens page in Split, the proxy's failing paths beside Grafana, in the Basics Demo
When the tabs don't fit one row, the row ends in **More**. It says how many screens it holds and how many of those aren't answering, such as *More 28 · 2 down*. It opens a list of every screen, each with its dot, and a search: type to narrow the list, Up and Down to move through it, and Enter to open a screen. Shift-click puts a screen in Split's right pane. The selected screen's tab, and in Split the right pane's, always stays in the row. A name too long for its tab shows in full in its tooltip. ## Linking to a Screen A link can say what the page shows, after its `#`: | Link | Shows | |---|---| | `/screens#all` | Every screen in the grid | | `/screens#agent-east` | One screen, as you left it, or where it starts the first time | | `/screens#agent-east/connection` | One screen, at its `url` plus `/connection`, query string included, such as `#proxy/activity?q=agent-rogue` | | `/screens#proxy/paths+grafana` | Two screens side by side, left then right | A screen's id in a link is its name in lowercase, each run of other characters a `-`; the proxy's is `proxy`. A [relayed agent dashboard](#agent-screens)'s tab answers to its agent's name the same way, so `/screens#coffee-shop-1-0` opens `coffee-shop-1.0`'s, unless a listed screen has that id. - A link with a path loads it, reloading a screen already open. A bare id only brings the screen up. - A `+` followed by a screen's id starts the second pane, so write a space in a query as `%20`, as the dashboards' search does in their address. - A link opened while the page is already open in another tab goes to that tab. The new tab closes itself, or, where the browser won't let it, says where the link went. ## Framing and Logins Every screen has to allow framing. The page can't tell a screen that refused it from a blank one, so such a screen looks empty; use **Open in a tab** for it. | Screen | Allows framing | |---|---| | The proxy's dashboard | always from this page, even with `proxy.dashboard.framingEnabled = false` (see [Exposure](https://prometheus-proxy.com/dashboard-exposure/index.md#exposure)) | | A direct agent dashboard | from 4.8.0, unless its `agent.dashboard.framingEnabled` is `false` | | Prometheus | always | | Grafana | only once `allow_embedding` is on, with `GF_SECURITY_ALLOW_EMBEDDING=true` in its environment | The page is behind the dashboard's [login](https://prometheus-proxy.com/web-dashboard/index.md#login), and signing in from a link into it returns to the screen and view the link named. Signing in with no page to return to, as after **Log out**, opens the page too. Each screen keeps its login, which it shows in its frame the first time. A login inside a frame works only when the screen is on the same site as the page, a scheme and a registered domain, since the dashboards' session cookies and Grafana's are `SameSite=Lax`. Otherwise, sign in with **Open in a tab**. For one login across every screen, put single sign-on in front of them all, such as an authenticating reverse proxy on one domain. The page is the proxy's, so while the proxy is down, a page already open keeps its frames but can't be reloaded. ## Startup Checks The proxy refuses to start with: - a screen whose name is blank, has no letter or digit, or is longer than 64 characters; - two names with the same id, or a name whose id is `proxy` or `all`; - a `url` that isn't an absolute `http` or `https` URL, or that carries a username or password, which the page would show anyone who can read the dashboard; - a `start` or a `probe` that doesn't begin with `/` or `?`; - more than 32 screens; - a `proxy.dashboard.path` of `/screens`, the page's path, while the page is served. A `url` read from an unset variable, as `${?GRAFANA_URL}` is, is empty, and the proxy refuses it, naming the screen. The dashboard's **Settings** view lists each screen with its `url`, its query values masked, and where it starts. ## Relayed Agent Dashboards { #agent-screens } !!! warning "Anyone who can read the screens page sees every agent" With `proxy.dashboard.agentScreens` on, every connected agent that allows it shows its name, host, target URLs, recent scrapes, activity, and settings to anyone who can read `/screens`. Agents allow it by default: `agent.dashboard.showOnProxy` is `true` unless set, whether or not `agent.dashboard.enabled` turns the agent's direct dashboard on. A direct agent dashboard's password doesn't guard the relayed one, which is behind the proxy's login. Before you turn `agentScreens` on, set `proxy.dashboard.password`, or bind `proxy.dashboard.host` to a private address. To keep one agent off every proxy, set its `agent.dashboard.showOnProxy = false`. The proxy logs a warning at startup when `agentScreens` is on with no password. With `proxy.dashboard.agentScreens = true`, the proxy shows each connected agent's dashboard in a separate tab, through the agent's gRPC connection: a relayed agent dashboard. A direct agent dashboard needs a port the proxy's users can reach, which an agent behind a firewall doesn't offer. For a relayed one, the agent opens no port, and its direct dashboard need not be on. A direct agent dashboard still shows what a relayed one can't, as for an agent that can't connect ([Direct and Relayed Agent Dashboards](https://prometheus-proxy.com/agent-dashboard/index.md#direct-and-relayed-agent-dashboards)). ```hocon proxy.dashboard { enabled = true agentScreens = true host = "127.0.0.1" password = ${?DASHBOARD_PASSWORD} } ``` ### What You See - **A tab for each agent that allows it**, after the listed screens, named for the agent. Its dot is green while the agent is connected and its relay is up. The agent's `agent_dashboard_relay_up` gauge has a series only while the agent is connected to a proxy that shows it here, and is 0 for the 5 seconds the relay waits, after a failure or after the proxy ended its streams, before it opens them again; `agent_dashboard_relay_failures_total` counts each failure ([Agent Metrics](https://prometheus-proxy.com/monitoring/index.md#agent-metrics)). - **A signal glyph** before the name, which says the tab is a relayed agent dashboard. It tells the tab from a listed screen, a direct agent dashboard listed by its URL included. Its tooltip and a screen reader say "through the proxy", and each pane's picker lists such agents in a separate group. - **The agent's views**, Paths, Connection, Activity, and Settings, in the same panes and layouts as any screen, and its Scrape now while both the agent's and the proxy's `scrapeNowEnabled` are on. Each agent's Scrape now runs up to four scrapes at once, apart from every other agent's and the proxy's own. - **The agent's state, not a second view of it.** The agent sends its state over the connection in batches when a page opens, and its changes after that. The proxy serves each agent's page at `/dashboard/agent-dashboard//`, under the dashboard's base path, behind the dashboard's login. ### Linking to an Agent's Tab A link names an agent's tab by the agent's name, as it names a listed screen by the screen's name: | Link | Opens | |---|---| | `/screens#agent-east` | agent-east's tab, whichever launch of it is connected | | `/screens#agent-east/connection` | agent-east's Connection view | | `/screens#agent.` | one launch's tab alone, by the launch ID the agent's Settings view shows | - An agent that restarts is a new launch with the same name, so a link by name opens the launch that's connected. The page's address uses the name too, so a link copied from it still opens the agent after a restart. - A listed screen of the same id comes first. - An agent names itself. While two connected agents give the same name, a link to it opens the proxy's tab rather than either, so neither can stand in for the other. - A link that names two screens, the first an agent that hasn't connected yet, opens that agent alone once it appears. ### Which Agents Appear - **The proxy's dashboard must be on.** `agentScreens` has no effect with `proxy.dashboard.enabled = false`. With it on, the proxy serves `/screens`, with its root redirect and framing, even with no `proxy.dashboard.screens` listed. - **The agent decides.** `agent.dashboard.showOnProxy`, `true` by default, lets a proxy with `agentScreens` on show the agent, and `false` keeps the agent's dashboard off every proxy. It doesn't depend on `agent.dashboard.enabled`: an agent with its direct dashboard off still shows on the proxy. An embedded agent, built in code, with the Ktor plugin, or with the Spring Boot starter, shows up the same way unless it opts out. - **Only connected agents.** A page opened after an agent left doesn't list it. An active/standby pair shows an agent's tab only on the proxy it's connected to, so the standby's page lists nothing until an agent fails over to it. An agent that can't connect never gets a tab. Its direct agent dashboard shows why ([Agent Can't Connect to the Proxy](https://prometheus-proxy.com/troubleshooting/index.md#agent-cant-connect-to-the-proxy)). - **A page already open keeps a gone agent's tab** for a while, shown down, with the last state it showed. A restarted agent is a new launch, which takes that tab over where it is, green again, its frame reloaded on the new launch's page. A second agent of the same name that connects while the first is still connected gets a separate tab, the two named with the start of their launch IDs while both are connected. - **A gone agent's tab goes** once the proxy drops the agent's launch, 10 minutes after the agent left or after the last page showing it closed, whichever is later, or as soon as a connected agent of the same name has a tab of its own, so the page holds one tab per name. A tab that's on screen stays until you leave it: the tab shown alone, either pane in **Split**, or a tile in or near the view in **All**. A listed screen never goes. ### What the Proxy Keeps The agent sends its state only while a page of it is open. The proxy drops a connected agent's state as the last page showing it closes. It keeps a gone agent's state only if a page showed its tab as the agent left. Only a tab that's shown holds a WebSocket session, counted in `proxy.dashboard.maxSessions`: a hidden tab, and a tile in **All** more than half a screen from the view, closes its socket and opens it again when it's shown. The proxy bounds what it keeps, measured as its estimate of the memory each state takes: | Limit | Value | When it's reached | |---|---|---| | One agent's state | 64 MiB; an agent at the defaults, 20,000 paths of 20 scrapes each, takes about 50 | The agent's page shows the part that fits, with the newest of its activity, and says it's larger than the proxy keeps | | Every agent's state together, a gone agent's whose page is open included | `proxy.dashboard.agentScreensMaxMBytes`, 96 MiB by default | The proxy lets go of gone agents' states, first those no page shows, then the rest, each the longest gone first; a page still open on one says so | | The heap those states take | Under 1.6 times the estimate | | | A gone agent's state | 10 minutes after the last page showing it closes | The proxy drops it | The proxy never lets go of a connected agent's state that a page shows. Past the total, a growing state shows the part that fits instead, and its page says the proxy's room for agents' states is full. When an agent sends its whole state again, as when its relay reconnects, its page keeps showing the old state while the new one fits beside it within the 64 MiB. Once the new one doesn't fit, the page shows it in part, saying the agent is sending it again, until the agent has sent all of it. The proxy's `proxy_agent_screens_partial` gauge counts the agents' pages shown in part, by `reason`: `too_large`, `total_full`, or `resending`. Lower `agentScreensMaxMBytes` for a small heap. Raise it, with the heap, for many large agents shown at once, as in **All**. The proxy's `proxy_agent_screens_bytes` gauge reports what the states hold, as it estimates their memory, and `proxy_agent_screens_max_bytes` the limit, which the proxy dashboard's Relayed Agent Dashboard Memory panel in [Grafana](https://prometheus-proxy.com/grafana/index.md) shows together: a total that stays at the limit means the proxy is letting go of gone agents' states, or showing agents in part. --- Source: https://prometheus-proxy.com/dashboard-exposure/ # Exposing the Proxy Dashboard The [dashboard](https://prometheus-proxy.com/web-dashboard/index.md) is off by default, and once on, anyone who can reach its port can read it until you set a [login](https://prometheus-proxy.com/web-dashboard/index.md#login). Before anyone but the proxy host reaches it, set what the list below names. The rest of the page puts the dashboard behind a reverse proxy, then says what it guards against on its own, which ports to firewall, how it runs on an HA pair, and what it costs the proxy. ## Before You Share It { #before-you-share-it } - **A login.** Set `proxy.dashboard.password`, from the environment as `DASHBOARD_PASSWORD` or from a Secret, and the dashboard asks for a login before it shows anything ([Login](https://prometheus-proxy.com/web-dashboard/index.md#login)). A login stops anyone who reaches the port; the settings below stop only a browser. - **A private address.** Keep the dashboard's port, 8094, on an internal network, or bind it to a private address with `proxy.dashboard.host`: `127.0.0.1` keeps it on the proxy host ([Ports](#why-it-is-on-its-own-port)). - **TLS in front of it.** The dashboard has no TLS, so put a reverse proxy that terminates TLS in front of it ([Behind a Reverse Proxy](#behind-a-reverse-proxy)). Over `https`, the dashboard marks its session cookie `Secure`. - **The reverse proxy's headers.** Have it pass the browser's `Host` on, or list the address viewers open in `proxy.dashboard.allowedOrigins`, so the live updates pass the [Origin check](#origin-check). - **The reverse proxy's address.** List it in `proxy.dashboard.trustedProxies`, so each viewer, not the reverse proxy, has a limit on wrong logins ([Client Addresses](#client-addresses)). - **The names viewers use.** List the host names viewers open the dashboard by in `proxy.dashboard.allowedHosts`, so it refuses a page that points a name it controls at it ([DNS rebinding](#dns-rebinding)). Two settings are yours to weigh: `proxy.dashboard.framingEnabled = false` refuses framing, which some policies and security scanners require ([Framing](#framing)), and `proxy.dashboard.scrapeNowEnabled = false` takes [Scrape now](#scrape-now) away from the dashboard's readers. `allowedOrigins`, `allowedHosts`, and `trustedProxies` are lists, so set them in a config file ([Dashboard configuration](https://prometheus-proxy.com/configuration/proxy/index.md#dashboard)). ## Behind a Reverse Proxy The dashboard's live updates come over a WebSocket, at `/dashboard/events`. A reverse proxy in front of it has to pass the WebSocket's handshake on, and the handshake has to pass the [Origin check](#origin-check). Two of nginx's defaults stop it: - With a plain `proxy_pass`, nginx passes each request as HTTP/1.0 and drops the `Upgrade` and `Connection` headers, so the dashboard answers the handshake with 400. - With those headers but nginx's default `Host`, the upstream's name, the browser's `Origin` doesn't match it. The dashboard refuses the handshake, Scrape now, and the login form with 403, and logs `Refused a dashboard request from origin …; add it to proxy.dashboard.allowedOrigins if expected`. Either way, without a login the page loads and its [live indicator](https://prometheus-proxy.com/web-dashboard/index.md#the-live-indicator) stays on **reconnecting…**. With a login, the login form is refused with 403, so the page never loads. Pass both headers, and the browser's `Host`: ```nginx # Connection: upgrade on a WebSocket handshake, and close on anything else. map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 443 ssl; ssl_certificate /etc/nginx/certs/server.pem; ssl_certificate_key /etc/nginx/certs/server.key; location /dashboard { proxy_pass http://proxy-host:8094; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $http_host; # The browser's address, which the dashboard reads once nginx is in proxy.dashboard.trustedProxies. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } # The screens page, outside the dashboard's path, which opens no WebSocket. location = /screens { proxy_pass http://proxy-host:8094; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } ``` `$http_host` is the `Host` header as the browser sent it, port included. `$host` drops the port, which breaks the match on a port other than the scheme's. To keep the `Host` nginx sets, list the address the browser opens in `proxy.dashboard.allowedOrigins` instead, for example `["https://dashboard.example.com"]`. Keep the path as it is. The page's links, its assets, and its WebSocket are all under `proxy.dashboard.path`, and the [screens page](https://prometheus-proxy.com/screens-page/index.md#screens) is at `/screens`, so a prefix nginx adds or strips breaks them. The session cookie is set at those two paths, so leave its paths alone too, rather than have nginx rewrite cookie paths. Over `https`, the dashboard marks its session cookie `Secure`. Every request reaches the dashboard from nginx's address. Until you list that address in `proxy.dashboard.trustedProxies`, the per-address limit on wrong logins is everyone's; see [Client Addresses](#client-addresses). A direct agent dashboard takes the same settings under `agent.dashboard`. The [nginx Demo](https://prometheus-proxy.com/nginx-demo/index.md) shows each step. ### Client Addresses { #client-addresses } The dashboard takes a client's address from its TCP connection, and uses it for: - the limit on wrong [logins](https://prometheus-proxy.com/web-dashboard/index.md#login), and the WARN for one; - the [Activity](https://prometheus-proxy.com/web-dashboard/index.md#the-activity-layout) row of a [Scrape now](https://prometheus-proxy.com/web-dashboard/index.md#scrape-now); - how often the INFO for a refused `Origin` or `Host` is logged. Behind a reverse proxy, that's the reverse proxy's address, so every user shares one limit, and the log and the Activity view name the reverse proxy. List the reverse proxies in `proxy.dashboard.trustedProxies`, each an IP address or a CIDR range. A request whose connection comes from one of them then takes the client's address from its `X-Forwarded-For` header instead: ```hocon proxy { dashboard { trustedProxies = ["10.0.0.5", "10.1.0.0/16"] } } ``` Each reverse proxy appends the address it heard from to the header. So the dashboard reads the header from the right, skips each listed proxy's address, and takes the first address that isn't one. Anything a client writes in the header itself is to the left of that, so it can't choose its address. - When every entry is a listed proxy, the dashboard takes the leftmost. - A request from a peer that isn't listed keeps the peer's address, its header ignored. So does one whose header, read from the right, holds something other than an IP address before the client's. - An entry may carry a port (`203.0.113.7:51000`, `[2001:db8::7]:4711`), which is dropped. - The dashboard reads only `X-Forwarded-For`, never `Forwarded` (RFC 7239): a reverse proxy that writes one passes a client's copy of the other on untouched. List only the reverse proxies' addresses, never a network their clients are on. List only reverse proxies that set the header or append to it in every location that forwards to the dashboard, as nginx's `$proxy_add_x_forwarded_for` does in both locations of the example above. A client that reaches the dashboard, or a listed reverse proxy, from a listed address can name any address it likes. So can one sent through a location that leaves the header out: nginx passes a client's header on untouched there, and a location with any `proxy_set_header` drops every one its `server` sets. The proxy logs the list at startup. It refuses to start with an entry that isn't an IP address or a CIDR range, a range with bits set past its prefix (`10.1.2.3/16`), or one that holds every address (`0.0.0.0/0`, `::/0`). Empty, the default, every client is its connection's peer. It's a list, so set it in a config file. The agent's dashboard reads `agent.dashboard.trustedProxies` the same way. ## Exposure Without a [login](https://prometheus-proxy.com/web-dashboard/index.md#login), anyone who can reach the dashboard's port can read it. Keep the port on an internal network, or bind it to a private address with `proxy.dashboard.host`. Without a login, the proxy warns at startup when the dashboard listens on all interfaces. With [relayed agent dashboards](https://prometheus-proxy.com/screens-page/index.md#agent-screens) on, the same reach shows every connected agent's dashboard too. A browser inside that network can still be used to reach it. A web page can do that in three ways. The dashboard guards against the first on its own, and against the other two with a setting each: - **A WebSocket from another site.** Browsers let any page open a WebSocket to any address, so the dashboard refuses a handshake whose `Origin` is not its host. Behind a reverse proxy that rewrites the Host header, the browser's origin is the proxy's public name, so list it in `proxy.dashboard.allowedOrigins`, or pass the browser's Host on; see [Behind a Reverse Proxy](#behind-a-reverse-proxy). The dashboard can't tell whether a reverse proxy in front of it terminates TLS, so it takes its host over `http` or `https`. An origin listed in `allowedOrigins` pins its scheme for its host and port. With `https://dash.example.com` listed, a page at `http://dash.example.com` is refused, though the Host the reverse proxy passes on matches. An origin must be `http` or `https`, a host, and an optional port, as a browser sends it. - **DNS rebinding.** A page can point its DNS name at the dashboard's address. The browser then sends that name as both `Origin` and `Host`, and the Origin check passes. List the names you reach the dashboard by in `proxy.dashboard.allowedHosts`, and it refuses any other host name with a 403, on every route. IP addresses, `localhost`, and the hosts in `allowedOrigins` are always allowed. This check is off until you set it. - **Framing.** A page can show the dashboard in a frame. That's allowed by default (`proxy.dashboard.framingEnabled`), so a portal or another page of yours can embed the dashboard, and so can a page on another site that a viewer opens. Such a page can hide the dashboard under its content and steer the viewer's clicks onto Scrape now or Log out, since the frame's requests come from the dashboard's page and pass the Origin check. It can't read what the frame shows. - With a login set, a page on another site gets only the login page, since the session cookie (`SameSite=Lax`) isn't sent to a frame on another site. So a login in a frame works only on the same site. A site is a scheme and a registered domain: a page on another port of the dashboard's host, or on a sibling subdomain, is on the same site, and frames the signed-in dashboard. - Set `proxy.dashboard.framingEnabled = false`, and every response forbids framing (`Content-Security-Policy: frame-ancestors 'none'`, and `X-Frame-Options: DENY` for older browsers), so no page, on any site, can frame it. - While the proxy serves the [screens page](https://prometheus-proxy.com/screens-page/index.md#screens), with screens listed or relayed agent dashboards on, `false` still lets the page show the dashboard. Every response then says `frame-ancestors 'self'` and `X-Frame-Options: SAMEORIGIN` instead, so only a page of the dashboard's origin can frame it. `allowedOrigins` and `allowedHosts` stop a browser, not someone who can reach the port directly; a login does. What framing lets a page do to the dashboard is small: it can't read the frame, and the only clicks it can steer are Scrape now, within its cooldown, and Log out. The setting is there mostly for audits. Security scanners such as ZAP, Burp, and Nessus flag a response with neither `X-Frame-Options` nor `frame-ancestors` as missing an anti-clickjacking header. So an organization that scans its internal services finds the dashboard by default, and `framingEnabled = false` answers that finding with one setting, no reverse proxy needed. If your policy requires the header and the dashboard is [behind a reverse proxy](#behind-a-reverse-proxy), you can add it there instead, as nginx does with: ```nginx add_header Content-Security-Policy "frame-ancestors 'none'" always; add_header X-Frame-Options DENY always; ``` The dashboard logs a request it refuses for its `Origin` or `Host` at INFO, naming the setting that would allow it. It does so at most once a minute for each address the requests come from, and logs the rest at DEBUG. It cuts the header to 270 characters, the longest a real one can be, and escapes its control characters, since a client sends it before any login. The Activity view shows the address each call with a bad token came from, so anyone who can read the dashboard can see who has tried the agent port. Anyone who can reach the dashboard, with its login when one is set, can also have the proxy [scrape a path](https://prometheus-proxy.com/web-dashboard/index.md#scrape-now) and read the first 2 KB of what it returns, even with the scrape port firewalled to Prometheus. Set `proxy.dashboard.scrapeNowEnabled = false` where that is more than the dashboard's readers should have. The route takes a request only from the dashboard's page. It applies the same Origin check as the WebSocket, and requires the header the page's script sends, which a page on another site can't add without the proxy's permission. So a link or form elsewhere can't make it scrape. A login doesn't replace these checks, so the dashboard keeps them with a login set, and checks the Origin of the login and Log out forms as well. Open pages, one WebSocket each, are capped at `proxy.dashboard.maxSessions` (default 50). A client that sends an oversized message is disconnected. So is one that stops reading, once 32 updates are waiting for it, which frees its place under the cap, so no one client can hold up the others' updates. A page's messages, which say what it shows, update it only when they change that, and at most once every 100 milliseconds, the first at once. So a client sending them in a loop can't have the proxy render its pages as fast as it sends. ## Why It Is on a Separate Port { #why-it-is-on-its-own-port } The proxy's admin port (8092) is a servlet container that cannot host WebSockets, so the dashboard could not live there even if that were desirable. It also turns out to be the safer arrangement. Kubernetes liveness and readiness probes target `/ping` on the admin port. If the dashboard shared that port, you could not firewall the dashboard without also cutting off your health probes. Ports in a fully-enabled proxy: | Port | Purpose | Default | |---|---|---| | 8080 | Prometheus scrapes | enabled | | 50051 | Agent gRPC connections | enabled | | 8082 | Proxy's own metrics | disabled | | 8092 | Admin servlets (`/ping`, `/healthcheck`, `/debug`) | disabled | | **8094** | **Dashboard** | **disabled** | ## Offline and Airgapped Deployments The dashboard loads no external assets. [htmx](https://htmx.org) ships inside the JAR as a WebJar dependency and is served from the classpath, so the dashboard renders with no outbound network access at all. That matters for this product specifically: a proxy exists to bridge a network boundary and frequently runs where outbound internet is restricted. A CDN-hosted script would leave a blank page in exactly that environment, and it would fail when someone opens the page during an incident, not at deploy time. ## Running an HA Pair Each proxy's dashboard shows **only the agents connected to that proxy**. With [proxy failover](https://prometheus-proxy.com/production/index.md#high-availability) configured, an agent holds one connection at a time, so it appears on exactly one dashboard. The same holds for [relayed agent dashboards](https://prometheus-proxy.com/screens-page/index.md#agent-screens): the standby's screens page shows an agent's only once it fails over to it. An agent that reached this proxy by failing over says so. Its detail panel shows the endpoint it connected through and its position in the configured list: ``` via proxy-b.example.com:50051 (2 of 2) [failed over] ``` The **failed over** marker appears whenever the agent is on anything other than its first endpoint, so an agent showing up on the standby is distinguishable from one starting fresh there. Agents with a single endpoint, or running a version predating this, show no position line. To follow one specific agent across the pair, use its **launch ID**. That value is generated once per agent process, so it survives a failover and identifies the same process on whichever proxy it lands on. The agent ID will *not* match: each proxy assigns a different one. ## Cost The dashboard adds little work to the scrape path: each scrape leaves a record in its path's history. Updates are driven by an internal event bus whose publish operation is non-blocking, so it can never delay an agent registration or a scrape. State is collected once per update and shared across every connected browser, so the cost does not scale with the number of open dashboards. Loading or reloading a page reuses that collection too, as long as it is less than `refreshIntervalSecs` old and no agent or path has changed since. So requesting pages in a loop can't make the proxy collect any faster. Counters that drift rather than change, such as backlog depth, map sizes, and eviction countdowns, refresh on `refreshIntervalSecs` rather than on every event. A page on the Activity view is sent its table only when the feed or its search has changed. [Agent screens](https://prometheus-proxy.com/screens-page/index.md#agent-screens) cost memory while a page shows an agent: see [What the Proxy Keeps](https://prometheus-proxy.com/screens-page/index.md#what-the-proxy-keeps). ## Limits - **One action.** Nothing on the dashboard changes the proxy's state. Its one action, [scrape now](https://prometheus-proxy.com/web-dashboard/index.md#scrape-now), scrapes a target as Prometheus would. - **One shared login, over plain HTTP.** The [login](https://prometheus-proxy.com/web-dashboard/index.md#login) is one username and password for everyone, and the dashboard has no TLS. Without a login, rely on network isolation, as with the admin port; see [Exposure](#exposure) for what the dashboard itself guards against. - **Consolidated paths show one agent's target.** When several agents register the same path, the row names one of them, with the others counted in the `+N`, and shows that agent's target URL and source. When it leaves, the row names the next agent and shows its target. The path's labels, which service discovery serves, stay the first registrant's. - **Departed paths age out.** A gone path stays for `departedPathRetentionSecs` (default 3600) after its agent left or its last scrape, whichever is later. At most 1,000 are kept at once, and none survives a proxy restart. - **An agent's recent scrapes are what its paths keep.** Its panel lists its latest 25 from the `pathHistorySize` scrapes (default 20) each path keeps. So an agent with one path lists at most 20, and a path shared with other agents holds theirs in the same 20. They go as their paths' histories do, and none survives a proxy restart. - **The activity feed is short-lived.** It keeps the last `activityLogSize` rows (default 500), and none survives a proxy restart. - **Agent screens are bounded in memory.** The proxy keeps at most 64 MiB of one agent's state, and `proxy.dashboard.agentScreensMaxMBytes` (96 by default) of every agent's together; see [What the Proxy Keeps](https://prometheus-proxy.com/screens-page/index.md#what-the-proxy-keeps). --- Source: https://prometheus-proxy.com/agent-dashboard/ # Agent Dashboard The proxy's [dashboard](https://prometheus-proxy.com/web-dashboard/index.md) shows each connected agent, its paths, and the scrapes the proxy saw. It can't show what happens on the agent's side of the firewall, and that's where the answer often is. An agent that can't reach its proxy never appears there. A path the proxy refused never registers. A target the agent scrapes is behind the firewall too. The agent's dashboard shows those. You open it as a direct agent dashboard, on the agent's port, or as a relayed agent dashboard, which a proxy shows on its screens page through the agent's connection ([Direct and Relayed Agent Dashboards](#direct-and-relayed-agent-dashboards)). Either way, it answers five questions: - **Is the agent connected?** If not, why not: each proxy endpoint, in failover order, with the last error the agent got connecting to it. - **Is each path registered?** Every path the agent has, configured or discovered, and for one the proxy refused, the proxy's reason, whether it's retried, and when. - **Is each target answering?** Each path's recent scrapes as the agent saw them: the target's status, how long the fetch took, and what the agent did with the body. A Scrape now button fetches a target from the agent at once, whether or not the proxy has the path. - **What is the agent doing with it?** Each path's metric filter and what it has dropped, the agent's discovery file and how its last read went, and the settings the agent resolved. - **What happened?** The agent's connection made, lost, and failed over, its paths registered and refused, and its discovery file failing, in the order they happened. !!! warning "Shown on proxies by default, and open until you set a password" The direct agent dashboard is off by default, but the dashboard isn't hidden: a proxy with `proxy.dashboard.agentScreens` on shows it as a relayed agent dashboard on its [screens page](https://prometheus-proxy.com/screens-page/index.md#agent-screens) to everyone who can sign in to that proxy's dashboard, unless `agent.dashboard.showOnProxy` is `false` ([Showing It as a Relayed Agent Dashboard](#showing-it-on-the-proxy)). There the proxy's login guards it, not the agent's. A direct agent dashboard, like the proxy's, has **no TLS**, and **no authentication until you set a password** (`agent.dashboard.password`, or `DASHBOARD_PASSWORD`). It listens on all interfaces by default, and without a login the agent logs a warning at startup when it does. Set `agent.dashboard.host` (or `--dashboard_host`) to `127.0.0.1` to keep it on the agent's host. Either way, it shows the agent's paths, target URLs (their passwords masked), proxy endpoints, and settings (never a token or password), so treat it as internal. !!! tip "See it running" Every demo's screens page shows its agents' relayed dashboards. The [Basics Demo](https://prometheus-proxy.com/basics-demo/index.md#an-agents-own-dashboard-shows-a-refused-path-and-a-lost-proxy) shows a refused path and a lost proxy, and Scrape now, and the [Network Demo](https://prometheus-proxy.com/network-demo/index.md#what-this-demo-shows) the proxies an agent fails over between. The [Kubernetes Demo](https://prometheus-proxy.com/kubernetes-demo/index.md#the-agents-own-dashboard-reached-with-kubectl-port-forward) shows it from a cluster that exposes nothing, as a relayed agent dashboard, and as a direct one through `kubectl port-forward`; the [Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md#the-agents-own-dashboard) and the [Spring Boot Demo](https://prometheus-proxy.com/spring-boot-demo/index.md#the-agents-dashboard) serve it from inside an app as well. ## Enabling the Direct Agent Dashboard { #enabling-it } === "Config file" ```hocon agent { dashboard { enabled = true port = 8095 // Its own port, after the agent's admin port (8093) path = "dashboard" // Served at http://:8095/dashboard host = "0.0.0.0" // "127.0.0.1" keeps it on the agent's host refreshIntervalSecs = 2 // How often the page is re-pushed pathHistorySize = 20 // Recent scrapes kept per path scrapeNowEnabled = true // A Scrape now button on each path activityLogSize = 500 // Lines kept in the Activity view username = "admin" // The login's username, once a password is set password = "" // Requires a login; better set as DASHBOARD_PASSWORD } } ``` === "Command line" ```bash java -jar prometheus-agent.jar --config agent.conf --dashboard --dashboard_port 8095 ``` === "Environment" ```bash DASHBOARD_ENABLED=true DASHBOARD_PORT=8095 java -jar prometheus-agent.jar --config agent.conf ``` === "Embedded agent" ```kotlin embeddedAgent { proxy("proxy.example.com") scrapeSelf(path = "my_app_metrics", port = 8080) dashboard(port = 8095, host = "127.0.0.1") }.start() ``` === "Helm" ```bash helm upgrade prometheus-agent ./charts/prometheus-agent --reuse-values --set dashboard.enabled=true kubectl port-forward deploy/prometheus-agent 8095 ``` Add `--namespace` and `-n` if you installed the agent in one, as the chart's README does in `monitoring`. The chart has the dashboard listen on the pod's loopback (`dashboard.host`, `127.0.0.1`) and keeps its port off the Service, so only `kubectl port-forward` reaches it; `dashboard.login.existingSecret` names a Secret holding the login's password. Then open `http://:8095/dashboard`. Turning it on restarts the agent, which interrupts the scrapes of the paths it serves. A proxy with `agentScreens` on shows a connected agent's relayed dashboard without that restart ([Showing It as a Relayed Agent Dashboard](#showing-it-on-the-proxy)). The flags and the environment variables have the same names as the proxy's, and each process reads them for its dashboard, as with the admin and metrics settings. The other settings, `maxSessions`, `allowedOrigins`, `allowedHosts`, `trustedProxies`, and `framingEnabled`, work as the proxy's do; see [Exposure](https://prometheus-proxy.com/dashboard-exposure/index.md#exposure). ## Showing It as a Relayed Agent Dashboard { #showing-it-on-the-proxy } A proxy with `proxy.dashboard.agentScreens` on can show this dashboard on its [screens page](https://prometheus-proxy.com/screens-page/index.md#agent-screens) as a relayed agent dashboard, through the agent's connection, with no port opened on the agent. `agent.dashboard.showOnProxy` allows it, and is `true` by default; it's independent of `agent.dashboard.enabled`, so an agent with its direct dashboard off still shows on the proxy. Set `showOnProxy = false` to keep it off every proxy: in the agent's config file, or as `-Dagent.dashboard.showOnProxy=false`, since it has no flag or environment variable; an embedded agent's is `setting("dashboard.showOnProxy", false)`, or the Spring Boot starter's or the Ktor plugin's `settings.dashboard.showOnProxy`. The Settings view shows it as Show on proxy. On the proxy, the page is behind the proxy's dashboard login, not the agent's, and everyone who can sign in there sees every agent that shows; see [The Dashboard on a Shared Proxy](https://prometheus-proxy.com/security/index.md#the-dashboard-on-a-shared-proxy). An agent that shows on a proxy keeps its activity feed from startup, within `activityLogSize`, though its direct dashboard is off, and its per-path scrape history, within `pathHistorySize`, only with its direct dashboard on or once a proxy asks for its relayed one. Because of that, `refreshIntervalSecs`, `pathHistorySize`, and `activityLogSize` must be positive unless both the direct dashboard and `showOnProxy` are off, or the agent refuses to start. ## Direct and Relayed Agent Dashboards The same dashboard reaches you two ways, and each shows what the other can't. A direct agent dashboard, on the agent's port, answers whether or not the agent is connected, so it can show why an agent can't reach its proxy, the first question above, which no proxy can show for an agent it never heard from. A relayed agent dashboard comes over the connection the agent already opened, so the agent opens no port, and one page shows every connected agent. | | Direct | Relayed | |---|---|---| | Turned on by | `agent.dashboard.enabled`: a restart of each agent | `proxy.dashboard.agentScreens`, with the proxy's dashboard on: one proxy restart for every agent | | Through the firewall | A port the viewer can reach: from inside the firewall, with `kubectl port-forward`, or over a VPN | Nothing opened on the agent | | Guarded by | The agent's own login, `agent.dashboard.password` | The proxy's dashboard login | | While the agent isn't connected | Answers, with why it can't connect | No tab; a page already open keeps its last state, shown down | | Through a failover | Answers throughout | Shown down on the old proxy's page, and on the new proxy's once the agent connects to it | | Scrape now | While the agent's `scrapeNowEnabled` is on | While both the agent's and the proxy's `scrapeNowEnabled` are on | Day to day, relayed agent dashboards are the ones to use: the proxy's screens page shows every connected agent's, with no port to open on any of them. Keep an agent's direct dashboard, reachable from inside the firewall, for when the agent won't connect or is failing over, and for an agent that no proxy shows (`showOnProxy = false`). To have both on one page, list the agent's direct dashboard as a screen too ([Listing Screens](https://prometheus-proxy.com/screens-page/index.md#listing-screens)), at an address the browser can reach. Its tab answers wherever the agent is connected, beside the relayed one, marked with a signal, while the agent is connected to that proxy. The [Network Demo](https://prometheus-proxy.com/network-demo/index.md)'s standby does this, since its agents connect to it only when they fail over. ## The Paths View The default view lists every path the agent knows about: those in `agent.pathConfigs`, those its [discovery file](https://prometheus-proxy.com/configuration/agent/index.md#dynamic-target-discovery) lists, and any registered at runtime. Each row has a light and a tag for where the path stands with the proxy: | State | Light | Tag | Meaning | |:-----------|:------|:--------|:---------------------------------------------------------------------------------------------------------| | registered | green | none | The proxy routes the path's scrapes to this agent | | retrying | red | amber | The proxy refused it for a cause that can clear, such as another agent holding it, or couldn't be asked, or another agent took it over | | refused | red | red | The proxy refused it for a cause that can't clear, such as an identity not allowed the path | | pending | red | neutral | Not registered yet: the agent isn't connected, or hasn't reached it | Under its URL, a path the proxy has scraped shows the status of its last scrape, then its recent scrapes as a strip of dots, oldest on the left, green for a success and red for a failure, and the share that succeeded. A registered path the proxy hasn't scraped says so: Prometheus isn't asking for it. Select a path to see its URL, its labels, and, while it isn't registered, the proxy's reason, when it was refused, and when the agent tries it again. [Registration Is Rejected](https://prometheus-proxy.com/troubleshooting/index.md#registration-is-rejected) says what each reason means, and how to fix it.
![agent-rogue's relayed dashboard on the screens page, its Paths view with two paths: /contractor_metrics, registered and answering 200, and /payments_metrics, refused and selected, under Refused by the proxy the reason "Agent identity 'contractor' is not authorized to register path /payments_metrics" and Next try "not until the agent reconnects"](https://prometheus-proxy.com/images/demo/agent.webp)
The Basics Demo's agent-rogue, its relayed dashboard on the proxy's screens page: a path its identity may not register, refused, with the proxy's reason
A path another agent took over, without consolidated mode, as a redeploy's new version or a copy of the agent deployed by mistake does, says so, and names that agent: the agent waits while the other serves the path, and takes it back as soon as no agent does, without reconnecting ([An Agent Is Connected but Serves No Paths](https://prometheus-proxy.com/troubleshooting/index.md#an-agent-is-connected-but-serves-no-paths)). A path with a [metric filter](https://prometheus-proxy.com/configuration/agent/index.md#metric-filtering) shows the filter's rules, how many lines and bytes it has dropped from Prometheus's scrapes, and whether it has ever let a scrape through unfiltered. **Recent scrapes** lists the path's last scrapes, newest first, as many as `pathHistorySize` keeps: when each ran, the target's status, how long the agent's fetch took, and what the agent did with the body. That's its size as the target sent it, its size after the filter when the filter dropped anything, and whether it was gzipped and sent to the proxy in chunks. A failed scrape shows the agent's reason, such as a refused connection or the agent's timeout. A scrape the proxy's dashboard asked for, with its Scrape now, is marked `from the proxy's dashboard`. The agent keeps these while its dashboard is on, or from the time a proxy that shows it accepts its connection, and only for scrapes the proxy asked for; it starts empty when the agent does. ## Scrape Now A selected path's **Scrape now** button fetches its target from the agent at once and shows the result above the list: the status, the size before and after the path's filter, its metric families and samples, and the start of the body as Prometheus would get it, after the filter. It works whether or not the proxy has the path, so the target of a path the proxy refused, or of an agent that can't connect, can still be checked. A browser names a path, never a URL: the agent scrapes only a path it has configured, discovered, or registered, at the URL it has for it. Like the proxy's, the button is limited to four scrapes at once and one per path every five seconds, and a scrape waits at most ten seconds for its target. A Scrape now leaves no trace in what the agent reports: not in its `agent_scrape_*` metrics, `agent_dashboard_scrapes_total`, its filter's counts, or the path's Recent scrapes. The agent logs it, with the address it came from. Turn the button off with `agent.dashboard.scrapeNowEnabled = false`. ## The Connection View
![agent-east's direct dashboard with its proxy stopped, its Connection view failing on proxy:50051: the endpoint tagged trying, beside the agent's last error, StatusException: UNAVAILABLE: io exception, and under Discovery its file, /discovery/targets.json, read every 5s, its last read ok, with no entries skipped](https://prometheus-proxy.com/images/demo/agent-connection.webp)
The Basics Demo's agent-east, its proxy stopped: the endpoint it keeps trying, with the error from its last try
The connection's state, `connected`, `connecting`, or `failing`, and the endpoint in use or being tried, marked `failed over` when it isn't the first. Under it: - **Proxy endpoints**, in failover order, each with the last error the agent got connecting to it, until a connect to it succeeds, once the proxy has registered the agent and its paths. A proxy that's down, a wrong port, a refused token, a TLS mismatch, and a proxy that refuses the agent or every one of its paths each show here, rather than only in the agent's log. [Agent Can't Connect to the Proxy](https://prometheus-proxy.com/troubleshooting/index.md#agent-cant-connect-to-the-proxy) and [TLS Handshake Failures](https://prometheus-proxy.com/troubleshooting/index.md#tls-handshake-failures) say how to fix each. - **Discovery**, when it's on: the file, how often it's read, whether the last read failed, and the entries it skipped, missing a path or a URL, or found colliding with a static path or listed twice. The agent's settings are on the [Settings view](#the-settings-view). ## The Activity View
![agent-east's Activity view with its proxy stopped, newest first: connect failed, with the agent's error, and disconnected, from proxy:50051; before them, three discovered paths registered, and its six paths taken over by agent-east-copy, then registered again](https://prometheus-proxy.com/images/demo/agent-activity.webp)
The Basics Demo's agent-east: its proxy lost, listed once, after its paths taken over by a copy of the agent and taken back
What has happened to the agent, newest first: the history the other views can't show, since they show only how things stand now. It's where you see that a path was refused just after the agent failed over, or that a connection dropped and came back while nobody was watching. | Event | Shown as | When | |:--------------------|:---------|:-----------------------------------------------------------------------------------------------| | connected | plain | The agent connected to a proxy endpoint | | disconnected | amber | A connection ended, with why when an error ended it | | connect failed | red | A connect failed, or the proxy refused the agent or all its paths; a repeat isn't listed again | | failed over | amber | The agent left its first endpoint for the next | | back to primary | plain | The agent went back to its first endpoint | | registered | plain | The proxy accepted a path, configured, discovered, or registered at runtime | | refused | red | The proxy refused a path, with its reason | | taken over | amber | The proxy gave a path to another agent, which it names | | unregistered | plain | A path was removed, such as one that left the discovery file | | discovery failed | red | The discovery file couldn't be read, so the agent keeps the paths it last read | | discovery recovered | plain | The discovery file was read again after it failed, with how many entries it has | | entries skipped | red | The discovery file listed entries without a single-segment path or a URL | | not filtered | red | A path's metric filter let a scrape through unfiltered, with why | Like events in a burst share a line, such as the agent registering its paths as it connects, counted and naming the first few paths. The same event again, such as failing over on every retry through a long outage, adds to the line it repeats. A proxy that keeps refusing the agent shows its connect, the refused paths, and **connect failed** once, and again only when the reason changes, not on every retry; the agent's connect and its paths show once the proxy takes them. An error shows as the first line of its message, up to 200 characters, here and in the other views; the agent's log has all of it. The view keeps `activityLogSize` lines (500), in memory, so a restart empties it. The search filters by event, path, with its slash or without, or detail, and **Problems only** keeps the red lines. The view updates as each line is added. ## The Settings View
![agent-east's Settings view: About, with its version, name, launch ID, start time, and config file; Proxy connection, with its endpoint, proxy:50051, its token set, and its reconnect pause, deadline, keepalives, and heartbeat; and the start of Scraping](https://prometheus-proxy.com/images/demo/agent-settings.webp)
The Settings view of the Basics Demo's agent-east
Every setting the agent resolved from its flags, environment variables, config, and defaults, as on the proxy's [Settings view](https://prometheus-proxy.com/web-dashboard/index.md#the-settings-layout): | Group | What it shows | |---|---| | About | the version, the agent's name, its launch ID, when it started, where its config came from, and the keys of any `-D` overrides | | Proxy connection | the proxy endpoints in failover order, whether a token is set, consolidated mode, the transport filter, the reconnect pause, gRPC deadlines and keepalive, and the heartbeat | | Scraping | the scrape timeout and retries, chunking and gzip thresholds, the largest scrape, HTTP client limits and cache, and how targets' certificates are checked | | Paths | how many paths are configured and filtered, how a refused path is retried, the backlog threshold, and discovery | | TLS | plaintext, TLS, or mutual TLS, where each certificate and key comes from, and the override authority | | Dashboard | where it listens, its login's username, its limits, what it keeps, and whether a proxy may show it | | Admin, Metrics, Tracing, Logging | each service's port and paths, the JVM metrics turned on, Zipkin, and the log level | No secret reaches the page: the agent's token, the trust store's password, the dashboard's password, and TLS material given as PEM show only as set or not set, and a `-D` override shows only its key. The page is sent the settings once when it opens, and again after the agent restarts. ## The Status Bar The bar along the top shows, on every view: - which agent the page is, after the logo: its name, as `Agent: agent-east`, the one the Settings view gives (`agent.name`, or `Unnamed-` and its host's name when none is set), so the dashboards of several agents are told apart at a glance; - whether the page is live, as on the proxy's dashboard; - the agent's connection state and endpoint; - how many paths it has, and how many aren't registered; - its backlog of scrapes waiting to run. The tab's title names the agent the same way and counts the problems, each path refused or retrying and a failing connection, as `(2 problems) Agent: agent-east`, so a dashboard in a background tab still says when something is wrong. At the bar's end, the theme button moves the dashboard through light, dark, and **auto**, the default, which follows your system's, a click at a time, as on the proxy's [dashboard](https://prometheus-proxy.com/web-dashboard/index.md#the-status-bar); the browser remembers the choice for each dashboard. --- Source: https://prometheus-proxy.com/onboarding/ # Onboarding a Team When several teams share one proxy, give each team a separate [identity](https://prometheus-proxy.com/security/index.md#per-agent-identities-and-path-authorization): a name, a token, and the path patterns its agents may register. A team here is a group that runs its agents. - **Impact.** The proxy reads identities only at startup, so adding one restarts it, and every team's agents reconnect. A proxy that can't read the new identity doesn't start, and while it's down, no team's paths are scraped. - **Check.** Before the restart, confirm the proxy will find the new token, and that no other identity has it ([step 3](#check-before-you-restart)). - **Change.** Make a token ([step 1](#choose-a-prefix-and-make-a-token)), add the identity ([step 2](#add-the-identity)), restart the proxy ([step 4](#restart-the-proxy)), and give the team its token ([step 5](#give-the-team-its-token)). - **Verify.** The proxy's log lists the new identity as it starts, and the dashboard shows the team's agents and paths ([step 6](#confirm-the-teams-agents-are-in)). - **Go back.** Put back the config step 2 copies, or roll back the Helm release, and every team's agents reconnect ([If It Doesn't Come Back](#if-it-doesnt-come-back)). ## 1. Choose a Prefix and Make a Token { #choose-a-prefix-and-make-a-token } Agree with the team on a prefix that every one of its paths will start with, such as `team_b_`. Then generate its token into a file that only you can read: ```bash (umask 077 && openssl rand -hex 32 > team-b-token) ``` The commands below read the token from `team-b-token`, so run them in the same directory. Make a new token for each team: the proxy refuses to start when two identities, or an identity and the shared `proxy.agentToken`, have the same one. ## 2. Add the Identity { #add-the-identity } This step, and steps 3 and 4, which change the proxy, have a tab for each way it runs, as in the [Quick Start](https://prometheus-proxy.com/getting-started/index.md). Choosing one opens the same tab in every step. The JAR tabs are for a proxy run by the systemd unit in [Running as a Service](https://prometheus-proxy.com/production/index.md#running-as-a-service), and each says what changes for one you run by hand with `nohup`, as the Quick Start does. The identity goes in the proxy's config. Its token goes in an environment variable that the config reads, so the config holds no token. Homebrew's service passes the proxy no variables, so there the token goes in the config. The identity's pattern, `team_b_*`, lets the team's agents register any path that starts with `team_b_`: `*` matches any run of characters, `?` exactly one, and any other character only itself, case included. A pattern is one segment, as a path is, so it may start with one `/` and has no other; see the Security page's [path patterns](https://prometheus-proxy.com/security/index.md#path-patterns) for the rest. === "JAR" These steps use the systemd unit in [Running as a Service](https://prometheus-proxy.com/production/index.md#running-as-a-service), with the config in `/etc/prometheus-proxy`. For a proxy you run by hand with `nohup`, as in the Quick Start, keep `./proxy.conf` and `./tokens.env` in the directory you start it from, and leave out `sudo` and `systemctl edit`: step 4 starts it with the variables in `./tokens.env`. First keep a copy of the config the proxy runs with now, to go back to: ```bash sudo cp /etc/prometheus-proxy/proxy.conf /etc/prometheus-proxy/proxy.conf.before-team-b ``` Add the identity, with its token read from a variable: ```hocon proxy.auth = [ // ...the identities already there { name = team-b token = ${TEAM_B_TOKEN} paths = ["team_b_*"] } ] ``` Set `TEAM_B_TOKEN` in the file the unit reads its environment from, beside the other identities' variables. The steps below use `/etc/prometheus-proxy/tokens.env`, which only root can read: ```bash sudo touch /etc/prometheus-proxy/tokens.env sudo chmod 600 /etc/prometheus-proxy/tokens.env echo "TEAM_B_TOKEN=$(cat team-b-token)" | sudo tee -a /etc/prometheus-proxy/tokens.env > /dev/null ``` If the unit doesn't name that file yet, run `sudo systemctl edit prometheus-proxy`, add these lines, and save: ```ini [Service] EnvironmentFile=/etc/prometheus-proxy/tokens.env ``` === "Homebrew" `brew services` starts the proxy without your shell's environment, and the formula's service sets no variables. So the token goes in the service's config, which you make readable only by you. Then keep a copy to go back to: ```bash CONF="$(brew --prefix)/etc/prometheus-proxy.conf" chmod 600 "$CONF" cp "$CONF" "$CONF.before-team-b" # The token, to write in the identity: cat team-b-token ``` Add the identity to `$(brew --prefix)/etc/prometheus-proxy.conf`, with the token in quotes: ```hocon proxy.auth = [ // ...the identities already there { name = team-b token = "" paths = ["team_b_*"] } ] ``` === "Docker" The container reads the proxy's config from a file it mounts, named by `PROXY_CONFIG`, as in [TLS with Docker](https://prometheus-proxy.com/docker/index.md#tls-with-docker). It gets its environment from an env file, named by `--env-file` or Compose's `env_file:`. The steps below use `./proxy.conf` and `./proxy.env`, in the directory you run `docker` from. Keep a copy of the config, to go back to, and make the env file readable only by you: ```bash cp proxy.conf proxy.conf.before-team-b touch proxy.env && chmod 600 proxy.env ``` Add the identity to `./proxy.conf`, with its token read from a variable: ```hocon proxy.auth = [ // ...the identities already there { name = team-b token = ${TEAM_B_TOKEN} paths = ["team_b_*"] } ] ``` Then add the variable to the env file: ```bash echo "TEAM_B_TOKEN=$(cat team-b-token)" >> proxy.env ``` Docker reads the env file only when it creates the container, so `docker restart` doesn't pass the new variable. Step 4 creates the container again. === "Helm" Put the token in a separate Secret, in the proxy's namespace: ```bash kubectl -n monitoring create secret generic proxy-auth-team-b \ --from-literal=token="$(cat team-b-token)" ``` Then add the identity to the values file the proxy's release was installed with, and its variable, read from that Secret. `helm upgrade` replaces `config` and `env` whole, so each keeps every team's entry: ```yaml # proxy-values.yaml config: | proxy { auth = [ { name = "team-a", token = ${TEAM_A_TOKEN}, paths = ["team_a_*"] } { name = "team-b", token = ${TEAM_B_TOKEN}, paths = ["team_b_*"] } ] } env: - name: TEAM_A_TOKEN valueFrom: { secretKeyRef: { name: proxy-auth-team-a, key: token } } - name: TEAM_B_TOKEN valueFrom: { secretKeyRef: { name: proxy-auth-team-b, key: token } } ``` The chart renders `config` into a ConfigMap, which anyone who can read the namespace's ConfigMaps can read, so the token stays in the Secret. To keep the whole config in a Secret instead, tokens and all, name that Secret in the chart's `existingSecret`. ## 3. Check Before You Restart { #check-before-you-restart } Check that the proxy, once restarted, will find a token for the new identity, and that no other identity has it: === "JAR" With the [systemd unit](https://prometheus-proxy.com/production/index.md#running-as-a-service): ```bash # Names tokens.env: systemctl show prometheus-proxy --property=EnvironmentFiles # 1: set, and not empty: sudo grep -c '^TEAM_B_TOKEN=.' /etc/prometheus-proxy/tokens.env # Nothing: no two tokens alike: sudo cut -d= -f2- /etc/prometheus-proxy/tokens.env | sort | uniq -d ``` The last check covers the tokens in that file. Compare a token set anywhere else, such as `proxy.agentToken` in the config, by hand. For a proxy you run by hand, skip the first check, and run the others on your file. === "Homebrew" ```bash CONF="$(brew --prefix)/etc/prometheus-proxy.conf" # 1: written once: grep -cF "$(cat team-b-token)" "$CONF" # Nothing: no two tokens alike: grep -Eo '[0-9a-f]{64}' "$CONF" | sort | uniq -d ``` The last check finds tokens made as step 1 makes them, 64 hexadecimal characters. Compare any other by hand. === "Docker" ```bash # 1: set, and not empty: grep -c '^TEAM_B_TOKEN=.' proxy.env # Nothing: no two tokens alike: grep '_TOKEN=' proxy.env | cut -d= -f2- | sort | uniq -d ``` The env file can hold other settings, so the last check compares only the variables that end in `_TOKEN`, the shared token's `AGENT_TOKEN` among them. Compare a token set anywhere else by hand. === "Helm" ```bash # The Secret the env entry names: kubectl -n monitoring get secret proxy-auth-team-b # The revision to go back to: helm history prometheus-proxy --namespace monitoring ``` The chart stops the old pod before it starts the new one, and the new pod can't start while a Secret or key that its `env` names is missing. So check each name in `env` against the Secrets. ## 4. Restart the Proxy { #restart-the-proxy } Every team's agents lose their connection, and a scrape that lands in between fails. Each agent reconnects on its own within seconds of the proxy being back, trying every `agent.internal.reconnectPauseSecs` (3 seconds by default), and registers its paths again. === "JAR" With the [systemd unit](https://prometheus-proxy.com/production/index.md#running-as-a-service): ```bash sudo systemctl restart prometheus-proxy journalctl -u prometheus-proxy -f # follow its log ``` ??? info "Run by hand" A proxy run with `nohup`, as in the Quick Start's Keep it running, gets its variables from the shell that starts it. Stop it, wait for it to exit, and start it again with the variables in `tokens.env`: ```bash kill "$(cat proxy.pid)" # Wait until it has exited and freed its ports: while kill -0 "$(cat proxy.pid)" 2>/dev/null; do sleep 1; done # Start it with the file's variables, in a subshell, so they stay out of your shell: (set -a && . ./tokens.env && exec nohup java -jar prometheus-proxy.jar --config proxy.conf > proxy.log 2>&1) & echo $! > proxy.pid tail -f proxy.log # follow its log ``` === "Homebrew" ```bash brew services restart prometheus-proxy tail -f "$(brew --prefix)/var/log/prometheus-proxy.log" # follow its log ``` === "Docker" Remove the container and create it again, so it gets the new variable. The command below gives it the ports, the config, and the env file. Add any other option you started it with, such as an `--env` for TLS: ```bash # The image it runs now, to run again: IMAGE=$(docker inspect --format '{{.Config.Image}}' prometheus-proxy) docker rm --force prometheus-proxy docker run --detach --name prometheus-proxy --restart unless-stopped \ -p 50051:50051 -p 127.0.0.1:8080:8080 \ --mount type=bind,source="$(pwd)"/proxy.conf,target=/app/proxy.conf \ --env PROXY_CONFIG=proxy.conf --env-file proxy.env \ "$IMAGE" docker logs --follow prometheus-proxy # follow its log ``` With Compose, whose service mounts the config and names the env file in `env_file:`, recreate the service, `proxy` here: ```bash docker compose up --detach --force-recreate proxy docker compose logs --follow proxy # follow its log ``` === "Helm" ```bash helm upgrade prometheus-proxy ./charts/prometheus-proxy --namespace monitoring --reuse-values -f proxy-values.yaml kubectl -n monitoring logs deploy/prometheus-proxy -f # follow its log ``` The log lists the identities the proxy read, then says it's up: ``` { .text .pp-output .pp-output--ok title="The proxy's log" } Per-agent auth enabled with identities: team-a, team-b All Proxy services healthy ``` ### If It Doesn't Come Back { #if-it-doesnt-come-back } A proxy that rejects its config logs why, after `Invalid configuration:`, and exits with status 1. Under systemd, Homebrew's service, Docker's restart policy, or Kubernetes, it starts again and fails the same way. Find the reason in its log, which step 4 follows: | The log says | What's wrong | |:---|:---| | `Could not resolve substitution to a value: ${TEAM_B_TOKEN}` | The variable isn't in the proxy's environment | | `proxy.auth identity 'team-b' has an empty token` | The variable is set, but empty | | `proxy.auth identities share a token: team-a, team-b` | Another identity has the same token, where `legacy-agent-token` is the shared `proxy.agentToken` | | `Duplicate proxy.auth identity names: team-b` | Another identity has the name | | `proxy.auth identity 'team-b' has path pattern 'team_b/*', which no path can match` | A pattern has a `/` after its first character | In Kubernetes, a missing Secret or key stops the pod before the proxy runs, so there's no log: `kubectl -n monitoring get pods` shows the pod in `CreateContainerConfigError`. Put the proxy back as it was, and every team's agents reconnect to it. Then correct the change, and make it again from step 2: === "JAR" With the [systemd unit](https://prometheus-proxy.com/production/index.md#running-as-a-service): ```bash sudo cp /etc/prometheus-proxy/proxy.conf.before-team-b /etc/prometheus-proxy/proxy.conf sudo systemctl restart prometheus-proxy ``` For a proxy you run by hand, copy the config back the same way, then start the proxy again as in step 4. === "Homebrew" ```bash CONF="$(brew --prefix)/etc/prometheus-proxy.conf" cp "$CONF.before-team-b" "$CONF" brew services restart prometheus-proxy ``` === "Docker" ```bash cp proxy.conf.before-team-b proxy.conf docker restart prometheus-proxy ``` The container mounts the file, so a restart reads the copy. The variable the container gained stays, unused. With Compose, run `docker compose restart proxy`. === "Helm" ```bash helm rollback prometheus-proxy --namespace monitoring # back to the revision before the upgrade ``` ## 5. Give the Team Its Token { #give-the-team-its-token } Send the token the way your organization shares secrets, then delete `team-b-token`. The team's agents present the token as `AGENT_TOKEN`, `--agent_token`, or `agent.agentToken`. They name their paths with the prefix, as `team_b_orders`, and keep their other settings, such as the proxy's address. Unlike the steps before, these tabs are for the team's agents, which needn't run the way the proxy does, so each is a place an agent can take its token from: === "Config file" The token comes from the agent's environment, through a substitution, so the config holds no token: ```hocon agent { agentToken = ${TEAM_B_TOKEN} pathConfigs = [ { name = "Orders", path = team_b_orders, url = "http://orders.internal:8080/metrics" } ] } ``` === "Environment" `AGENT_TOKEN` takes precedence over the config file's token, and the paths stay in the config file. Here the team keeps the token in a separate file, `team-b-token`: ```bash # agent.conf lists the agent's paths, each starting with team_b_ AGENT_TOKEN="$(cat team-b-token)" java -jar prometheus-agent.jar --config agent.conf ``` An agent's container takes it the same way, from `--env` or an env file. === "Helm" Put the token in a Secret in the agent's namespace, which the agent's chart reads into `AGENT_TOKEN`. Here the team keeps the token in a separate file, `team-b-token`: ```bash kubectl -n team-b create secret generic agent-token \ --from-literal=token="$(cat team-b-token)" ``` ```yaml # agent-values.yaml proxy: hostname: proxy.example.com:50051 agentToken: existingSecret: agent-token # its key is token, the chart's default config: | agent { pathConfigs: [ { name: "Orders", path: team_b_orders, url: "http://orders.team-b.svc.cluster.local:8080/metrics" } ] } ``` Tell the team, too, whether the proxy shows relayed agent dashboards on its screens page. With `proxy.dashboard.agentScreens` on, each agent's relayed dashboard appears there, with its paths, target URLs, scrapes, and activity. Everyone who can sign in to the proxy's dashboard sees it, other teams included, unless the agent sets `agent.dashboard.showOnProxy = false` (see [The Dashboard on a Shared Proxy](https://prometheus-proxy.com/security/index.md#the-dashboard-on-a-shared-proxy)). ## 6. Confirm the Team's Agents Are In { #confirm-the-teams-agents-are-in } With the proxy's [dashboard](https://prometheus-proxy.com/web-dashboard/index.md) on, three of its views show the team in place: - **Settings** lists `team-b` and its patterns under Agent authentication. - **Agents** shows each of the team's agents, with `team-b` as its identity. - **Paths**, searched with `?q=team-b`, shows the paths the team's agents registered. A path outside the team's patterns appears in the **Activity** view as `rejected`, with the reason, and on the team's [agent dashboard](https://prometheus-proxy.com/agent-dashboard/index.md), where it's on, as refused. With the dashboard off, the proxy's log tells the same. It logs each path it adds, so the team's prefix finds them: ``` { .text .pp-output .pp-output--ok title="The proxy's log" } Added path /team_b_orders for agentId 12 ``` A path outside the team's patterns, and an agent whose token the proxy doesn't know, are logged at WARN: ``` { .text .pp-output title="The proxy's log" } Agent identity 'team-b' denied registration of path /orders Refused an agent from 10.0.4.17 (UNAUTHENTICATED): it sent an unknown agent token ``` With the proxy's metrics on, `proxy_path_rejections_total{cause="not_authorized"}` and `proxy_agent_auth_failures_total{reason="unknown_token"}` count them. ## Taking a Team's Access Away { #taking-a-teams-access-away } Remove the team's identity from the config, and with Helm, its entry in `env`. Then restart the proxy as in step 4, with the same check before and the same way back. From then on the proxy refuses the team's agents with `UNAUTHENTICATED`, and their paths leave it. Remove the team's variable, or delete its Secret, only once the restarted proxy is up: the config you'd go back to still names it. With Homebrew, the token goes with the identity. --- Source: https://prometheus-proxy.com/upgrading/ # Upgrading Upgrade the shared proxy first, once, in a window you announce. Each team upgrades its agents later, when it suits the team, since a proxy and agents of different releases work together ([Versions That Work Together](#versions-that-work-together)). - **Impact.** Every team's scrapes go through the proxy, so its restart changes all of them at once: no path is scraped, every agent reconnects, and the dashboard loses its Activity view, each path's History, and its sign-ins ([What a Proxy Restart Interrupts](#what-a-proxy-restart-interrupts)). - **Check.** Read what the new release refuses at startup, and note how many agents and paths the proxy has ([step 1](#check-before-you-upgrade)). - **Upgrade.** Put the new release in place and restart the proxy ([step 2](#upgrade-the-proxy)). Then each team upgrades its agents ([step 3](#upgrade-the-agents)). With a primary and a standby, upgrade the primary first ([Which to Upgrade First](#which-to-upgrade-first)). - **Verify.** The proxy's log says it's up, and the agent and path counts match what you noted ([step 2](#confirm-the-upgrade)). - **Go back.** Put the previous release back, and every team's agents reconnect to it ([Going Back](#going-back)). For an app that embeds the agent, [Upgrading an Embedded Agent](https://prometheus-proxy.com/embedded-upgrading/index.md) covers what its code sees. ## 1. Check Before You Upgrade { #check-before-you-upgrade } Find out which releases you run. The proxy and the agent each log their version as they start, as `--version` prints it. From 4.7.0 on, their metrics give it too, in the `version` label of `proxy_build_info` and `agent_build_info`. An agent whose metrics are scraped without `agent_build_info` is older: ```promql count by (version) (agent_build_info) ``` Then read the "Before you upgrade" section of each release between yours and the new one, in the [release notes](https://github.com/pambrose/prometheus-proxy/blob/master/RELEASE_NOTES.md). It lists the changes you have to act on first. Look hardest for what the new release refuses at startup: a proxy that refuses its config doesn't start, and while it's down, no team's paths are scraped. The boxes below give what the last three releases change for a standalone proxy and its agents. From 4.8.0, read the first; from 4.7.0, open the second too, and from 4.6.x, the third as well. !!! note "Upgrading from 4.8.0" A proxy or an agent that starts on 4.8.0 starts on 4.9.0 too. After the upgrade: - Each logs a WARN at startup for each key of its config section, `proxy` or `agent`, that isn't a setting, naming the nearest one. Such a key never had an effect: fix its name, or remove it. - The proxy's and the agents' Grafana dashboards, and `grafana/alerts.yml`, have panels and alerts for 4.9.0's new metrics: import them again. - On the [screens page](https://prometheus-proxy.com/screens-page/index.md), give a Prometheus screen `probe = "/-/healthy"`, which stops the browser's console logging an error every 5 seconds. An app written in Kotlin that embeds the agent needs Kotlin 2.4 or later to compile ([Upgrading an Embedded Agent](https://prometheus-proxy.com/embedded-upgrading/index.md#upgrading-from-480)). ??? warning "Upgrading from 4.7.0" The proxy: - Refuses to start with a `proxy.auth` pattern that has a `/` after its leading one, such as `team_a/*`. With service discovery on, it also refuses a `proxy.service.discovery.path` of whitespace, `/` alone, or two leading slashes. A pattern with one leading slash, such as `/team_a_*`, now matches, where it matched no path. - Lets any page frame its dashboard, and so do the agents, where 4.7.0 refused framing on both. To keep refusing it, set `proxy.dashboard.framingEnabled = false`, and `agent.dashboard.framingEnabled = false` on an agent whose dashboard is on. - Pins each origin in `proxy.dashboard.allowedOrigins` to its scheme: if viewers open the dashboard over both `http` and `https`, list both origins. - Answers a script that sends the dashboard's login as Basic Auth with a browser's headers as it answers a browser, with the login page or a 401. Those headers are `Accept: text/html`, `Upgrade-Insecure-Requests`, `Origin`, and `Referer`; drop them from the script. - In the Helm charts, runs its pods, and the agents', without a Kubernetes API token. If something added to the pod needs one, such as a sidecar, set the chart's `automountServiceAccountToken` to `true`. The agents: - Refuse to start with a configured path of more than one segment, such as `app/metrics` or `//metrics`, or with a proxy endpoint they can't dial, such as `:50051` or `[::1]50051`. A discovered path of more than one segment is skipped. - Keep their activity feed in memory from startup, within `agent.dashboard.activityLogSize`, even with their dashboard off. They refuse to start with an `agent.dashboard.refreshIntervalSecs`, `pathHistorySize`, or `activityLogSize` that isn't positive. An agent with its direct dashboard off and `agent.dashboard.showOnProxy = false` does neither, and shows on no proxy's screens page. ??? warning "Upgrading from 4.6.x" The proxy: - Refuses a path with more than 64 labels, `proxy.internal.maxLabelsPerPath`, and a path past the 100,000 that one identity's agents may register together, `proxy.internal.maxPathsPerIdentity`. With agent auth off, or every agent on the shared `proxy.agentToken`, every agent is one identity, so the limit counts your whole fleet. Raise either, or set it to `0` for none, before you upgrade. They apply to agents of any release. - Refuses framing on every dashboard response, as the agents do; 4.8.0 allows it again by default. - In the Helm chart, listens for its dashboard on the pod's loopback only (`dashboard.host`, `127.0.0.1`). To publish the dashboard through a Service or an Ingress you add, set `dashboard.host` to `0.0.0.0`, and require a login. - In `etc/compose/proxy.yml`, publishes its ports on `127.0.0.1` only, and the agents' port, 50051, not at all. The agents: - Read `DASHBOARD_ENABLED`, `DASHBOARD_PORT`, `DASHBOARD_PATH`, `DASHBOARD_HOST`, `DASHBOARD_USERNAME`, `DASHBOARD_PASSWORD`, and `METRICS_PROXY_PATH`, which only the proxy read, or nothing did. An agent whose environment sets them, such as one that shares the proxy's env file, opens its direct dashboard, on port 8095 unless `DASHBOARD_PORT` names another, or serves its metrics at that path. It refuses to start on a value it can't parse, or on a dashboard port that's taken. Check each agent's environment before you upgrade it. Note how many agents are connected and how many paths are registered, to compare after the upgrade. `proxy_agent_map_size` and `proxy_path_map_size` give them, and so do the dashboard's Agents and Paths views. Then tell the teams when the proxy will restart. ## 2. Upgrade the Proxy { #upgrade-the-proxy } In the JAR, Docker, and Helm tabs, the first command sets `NEW` to `x.y.z`. Change it to the release you're upgrading to, as its [release page](https://github.com/pambrose/prometheus-proxy/releases) names it. === "JAR" These commands are for a proxy run by the systemd unit in [Running as a Service](https://prometheus-proxy.com/production/index.md#running-as-a-service). Download the new JAR beside the running one, and check its version: ```bash NEW=x.y.z # the release you're upgrading to BASE=https://github.com/pambrose/prometheus-proxy/releases/download/$NEW cd /opt/prometheus-proxy sudo curl -fLo prometheus-proxy.jar.new "$BASE/prometheus-proxy.jar" # Prints Version: and the new release: java -jar prometheus-proxy.jar.new --version ``` Once it prints the new release, keep the running JAR to go back to. Then move the new one into place, so the running proxy's JAR isn't written over, and restart the proxy: ```bash cd /opt/prometheus-proxy sudo cp prometheus-proxy.jar prometheus-proxy.jar.previous sudo mv prometheus-proxy.jar.new prometheus-proxy.jar && sudo systemctl restart prometheus-proxy journalctl -u prometheus-proxy -f # follow its log ``` === "Homebrew" The tap has only its current release, so note the one you run first: going back runs its JAR. ```bash # The release you run now: brew list --versions prometheus-proxy brew update brew upgrade pambrose/tap/prometheus-proxy brew services restart prometheus-proxy # Follow its log: tail -f "$(brew --prefix)/var/log/prometheus-proxy.log" ``` The upgrade keeps a `prometheus-proxy.conf` you've edited, and puts the new release's default beside it, as `prometheus-proxy.conf.default`. === "Docker" Pull the new image before you stop the container, so the gap is only the start: ```bash NEW=x.y.z # the release you're upgrading to docker pull "pambrose/prometheus-proxy:$NEW" # Its IMAGE column has the tag to go back to: docker ps --filter name=prometheus-proxy ``` Once the pull succeeds, stop and remove the container: ```bash docker stop prometheus-proxy && docker rm prometheus-proxy ``` Then start it with the `docker run` you started it with, with `pambrose/prometheus-proxy:$NEW` as its image. For [Production Setup](https://prometheus-proxy.com/docker/index.md#production-setup)'s, run this from the directory that holds its certificate, key, and token: ```bash docker run --detach --name prometheus-proxy \ -p 50051:50051 \ -p 127.0.0.1:8080:8080 \ -p 127.0.0.1:8082:8082 \ -p 127.0.0.1:8092:8092 \ --env CERT_CHAIN_PEM="$(base64 < server.crt | tr -d '\n')" \ --env PRIVATE_KEY_PEM="$(base64 < server.key | tr -d '\n')" \ --env AGENT_TOKEN="$(cat agent-token)" \ --env ADMIN_ENABLED=true \ --env METRICS_ENABLED=true \ --restart unless-stopped \ "pambrose/prometheus-proxy:$NEW" ``` With Compose, change the image's tag in the compose file, and run `docker compose up --detach`. It recreates each container whose image changed. === "Helm" Clone the repository at the new release, whose charts run its images. Then upgrade the release with the values file it was installed with: ```bash NEW=x.y.z # the release you're upgrading to git clone -c advice.detachedHead=false --depth 1 --branch "$NEW" \ https://github.com/pambrose/prometheus-proxy.git "prometheus-proxy-$NEW" # The revision to go back to: helm history prometheus-proxy --namespace monitoring helm upgrade prometheus-proxy \ "prometheus-proxy-$NEW/charts/prometheus-proxy" \ --namespace monitoring -f proxy-values.yaml # Wait for the new pod, then follow its log: kubectl -n monitoring rollout status deployment/prometheus-proxy kubectl -n monitoring logs deploy/prometheus-proxy -f ``` Without that file, `helm get values prometheus-proxy --namespace monitoring -o yaml > proxy-values.yaml` writes the values the release has. If it sets `image.tag`, change it to the new release, or remove it: unset, the chart runs its release's image. The log gives the new release's version and says the proxy is up. Then it logs each agent's paths as the agent reconnects and registers them again: ``` { .text .pp-output .pp-output--ok title="The proxy's log" } All Proxy services healthy Added path /team_b_orders for agentId 12 ``` Once the agents are back, `proxy_agent_map_size` and `proxy_path_map_size`, or the dashboard's Agents and Paths views, match what you noted. `proxy_build_info` gives the new version. ### Going Back { #going-back } If the new release refuses the proxy's config, it logs why, after `Invalid configuration:`, and exits with status 1 (see [The Proxy or Agent Exits at Startup](https://prometheus-proxy.com/troubleshooting/index.md#the-proxy-or-agent-exits-at-startup)). Its supervisor starts it again, and it fails the same way. Correct the setting, as the release notes say. Or put the previous release back, as for any other problem the upgrade brings, and every team's agents reconnect to it: === "JAR" ```bash cd /opt/prometheus-proxy sudo mv prometheus-proxy.jar.previous prometheus-proxy.jar sudo systemctl restart prometheus-proxy ``` === "Homebrew" Homebrew can't install the previous release, since the tap has only its current one. Until a release fixes what sent you back, run the previous release's JAR with the service's config. Set `OLD` to the release you upgraded from, as `brew list --versions` showed it, and download its JAR: ```bash OLD=x.y.z # the release you upgraded from BASE=https://github.com/pambrose/prometheus-proxy/releases/download/$OLD curl -fLO "$BASE/prometheus-proxy.jar" ``` Once it's downloaded, stop the service, and run the JAR on the Java the formula installed. It runs in your terminal until you stop it with Ctrl+C: ```bash brew services stop prometheus-proxy "$(brew --prefix openjdk@25)/bin/java" -jar prometheus-proxy.jar \ --config "$(brew --prefix)/etc/prometheus-proxy.conf" ``` To keep it running after you close the terminal, start it with `nohup`, as in the Quick Start's [Keep it running](https://prometheus-proxy.com/getting-started/index.md#start-the-proxy). === "Docker" Set `OLD` to the tag `docker ps` showed before the upgrade, and stop and remove the new release's container: ```bash OLD=x.y.z # the release you upgraded from, as docker ps showed it docker stop prometheus-proxy && docker rm prometheus-proxy ``` Then start it with the `docker run` you started it with, with `pambrose/prometheus-proxy:$OLD` as its image. For [Production Setup](https://prometheus-proxy.com/docker/index.md#production-setup)'s, run this from the directory that holds its certificate, key, and token: ```bash docker run --detach --name prometheus-proxy \ -p 50051:50051 \ -p 127.0.0.1:8080:8080 \ -p 127.0.0.1:8082:8082 \ -p 127.0.0.1:8092:8092 \ --env CERT_CHAIN_PEM="$(base64 < server.crt | tr -d '\n')" \ --env PRIVATE_KEY_PEM="$(base64 < server.key | tr -d '\n')" \ --env AGENT_TOKEN="$(cat agent-token)" \ --env ADMIN_ENABLED=true \ --env METRICS_ENABLED=true \ --restart unless-stopped \ "pambrose/prometheus-proxy:$OLD" ``` With Compose, put the previous tag back in the compose file, and run `docker compose up --detach`. === "Helm" ```bash # Back to the revision before the upgrade: helm rollback prometheus-proxy --namespace monitoring ``` It restores the previous revision's chart and values, and so its image. Going back from 4.8.0 to 4.7.0, the config loads as it is, since 4.7.0 ignores the settings it doesn't have, but: - A `proxy.auth` pattern with a leading slash, such as `/team_a_*`, matches no path on 4.7.0, so that identity's agents can register none of their paths. Write it as `team_a_*` before you go back. - The screens page, `/screens`, is gone, and with it the relayed agent dashboards. - Every dashboard refuses to be framed again, whatever `framingEnabled` says, so a page of yours that frames one shows nothing there. - `proxy.dashboard.trustedProxies` does nothing, so behind a reverse proxy, every viewer shares one limit on wrong logins again. ## 3. Upgrade the Agents { #upgrade-the-agents } Each team upgrades its agents the same way, with `prometheus-agent` in place of `prometheus-proxy`. That covers its JAR, unit, formula, image, container, and chart, with the agent's values file and namespace. An agent's restart takes only its paths off the proxy. Their scrapes fail until it registers them again, seconds after it starts, unless another agent serves the same path in [consolidated mode](https://prometheus-proxy.com/advanced/index.md#consolidated-mode). It logs: ``` { .text .pp-output .pp-output--ok title="The agent's log" } Connected to proxy at proxy-host.example.com:50051 using plaintext Sending stream keepalives to proxy proxy-host.example.com after 30s without a result Registered http://localhost:9100/metrics as /my_app_metrics with labels {} (static) ``` With `proxy.dashboard.agentScreens` on, an agent from 4.8.0 on also logs `Proxy proxy-host.example.com shows this agent's dashboard on its screens page`, and gets a tab there for its relayed dashboard. An agent whose config the new release refuses logs why, after `Invalid configuration:`, and exits. Step 1's [release changes](#what-each-release-changes) name what each release refuses. Going back is as for the proxy. ## What a Proxy Restart Interrupts - **Scrapes.** None of the proxy's paths is scraped until the proxy is back and each agent has registered its paths again, so Prometheus records those scrapes as failed, `up` 0. - **Every agent's connection.** Each agent tries to reconnect every `agent.internal.reconnectPauseSecs`, 3 seconds by default, so it's back within seconds of the proxy. An agent from 4.6.0 or earlier with one proxy endpoint waits out gRPC's backoff instead. That backoff grows the longer the proxy is down, up to 2 minutes, so such an agent can return that much later. - **Failover.** An agent with more than one endpoint in `agent.proxy.endpoints` moves to the next, and returns to the first at its next reconnect. - **The pod, in Kubernetes.** The chart replaces the proxy's pod with the `Recreate` strategy: it stops the old pod before it starts the new one. So the gap includes the JVM's start, and pulling the new image if the node doesn't have it. - **The dashboard.** The proxy keeps its Activity view, each path's History, and its sign-ins in memory, so they start empty, and everyone signs in again. ## Which to Upgrade First Upgrade the proxy first, then the agents. That way the shared proxy restarts only once, and a newer proxy with older agents is the pairing the nginx demo runs. Each team's agents gain the features that need both sides as the team upgrades them. With `proxy.dashboard.agentScreens` on, every agent upgraded to 4.8.0 or later shows its relayed dashboard on the proxy's screens page, with its paths, target URLs, scrapes, and activity. Everyone who can sign in to the proxy's dashboard sees it, other teams included, unless the agent sets `agent.dashboard.showOnProxy = false`. Tell each team before it upgrades (see [The Dashboard on a Shared Proxy](https://prometheus-proxy.com/security/index.md#the-dashboard-on-a-shared-proxy)). With a [primary and a standby](https://prometheus-proxy.com/production/index.md#high-availability), upgrade the primary first. Its agents fail over to the standby within seconds, and stay there. Once the primary is back, give it a few seconds, then upgrade the standby: its restart sends each agent back to the first endpoint in its list, the upgraded primary. In the other order, the agents stay on the standby after the primary's upgrade, until their connection to it drops. `AgentNotOnPrimary`, in `grafana/alerts.yml`, fires for each agent left on a backup endpoint for 30 minutes. ## Versions That Work Together When an agent registers, it and the proxy each say which newer features they support. Each uses a feature only when the other supports it too, and otherwise behaves as its release did before. So a proxy and agents of different releases still connect, register their paths, and scrape. A mixed pair goes without only the features its older side lacks. Each of these needs both the proxy and the agent on the release named, or later: - **Stream keepalives, 4.7.0**, which keep a reverse proxy's idle timeout from closing an agent's streams. Without them, an agent behind nginx or another reverse proxy is cut off whenever a stream stays quiet for the idle timeout, and reconnects. Until both are upgraded, raise the timeouts ([nginx Reverse Proxy](https://prometheus-proxy.com/advanced/index.md#nginx-reverse-proxy)). - **Takeover notices, 4.7.0**, which tell an agent that another agent took its path. Without them, the displaced agent shows the path as registered, and takes it back only when it reconnects ([An Agent Is Connected but Serves No Paths](https://prometheus-proxy.com/troubleshooting/index.md#an-agent-is-connected-but-serves-no-paths)). - **Agents' dashboards on the [screens page](https://prometheus-proxy.com/screens-page/index.md#agent-screens), 4.8.0.** An agent from 4.7.0 or earlier gets no tab there. The project names no range of releases that work together, and its tests run a proxy and agents of the same release. The [nginx demo](https://prometheus-proxy.com/nginx-demo/index.md#nginxs-stream-timeouts-cut-off-an-agent-from-460-every-minute) does mix them: its proxy is the current release, and one of its agents runs 4.6.0 on purpose. An agent newer than its proxy says, as it connects, which of these the proxy lacks: ``` { .text .pp-output title="The agent's log, with a proxy from 4.6.0" } Sending no stream keepalives to proxy proxy-host.example.com: it gives no interval Proxy proxy-host.example.com predates path notices; a path another agent takes over stays shown here ``` --- Source: https://prometheus-proxy.com/monitoring/ # Monitoring Both the proxy and agent expose operational metrics and admin endpoints. ## Enabling Metrics Metrics are disabled by default. Enable them via CLI, environment variables, or config file. === "Proxy" ```hocon proxy { metrics { enabled = true port = 8082 path = "metrics" } admin { enabled = true port = 8092 } } ``` Or via CLI: `--metrics` or `METRICS_ENABLED=true` Default endpoint: `http://proxy-host:8082/metrics` === "Agent" ```hocon agent { metrics { enabled = true port = 8083 path = "metrics" } admin { enabled = true port = 8093 } } ``` Or via CLI: `--metrics` or `METRICS_ENABLED=true` Default endpoint: `http://agent-host:8083/metrics`. Since 4.7.0, an agent can serve its metrics through the proxy instead, with no port (see [Scraping Internal Metrics](#scraping-internal-metrics)). ### Scraping Internal Metrics The proxy runs next to Prometheus, so Prometheus scrapes its metrics port directly. The agents sit behind firewalls, where Prometheus can't reach their ports, so it scrapes each agent's metrics through the proxy, at a path of the agent's own, one job per agent (the Agents dashboard tells agents apart by `job`). Since 4.7.0, the agent serves them at that path itself, read in-process, with no metrics port to open (`agent.metrics.proxyPath`): ```hocon agent { metrics { // Served through the proxy at /cluster_a_agent_metrics, read in-process, with no port proxyPath = cluster_a_agent_metrics // Optional: the path's labels in the proxy's service discovery, as JSON proxyPathLabels = "{\"cluster\": \"a\"}" } } ``` Or via CLI: `--metrics_proxy_path cluster_a_agent_metrics` or `METRICS_PROXY_PATH=cluster_a_agent_metrics`. Its labels, `agent.metrics.proxyPathLabels`, are the path's labels in the proxy's [service discovery](https://prometheus-proxy.com/service-discovery/index.md), as a `pathConfigs` entry's are, and only the config sets them. The path is checked as a `pathConfigs` entry is: one another path also names, or that has a character the proxy refuses, stops the agent at startup. Give each agent a separate path, as each is a separate job. Agents that share a config file, such as replicas or the agents of a [consolidated](https://prometheus-proxy.com/advanced/index.md#consolidated-mode) path, would otherwise name the same one, and the proxy would serve one agent there, or, consolidated, one job for them all. Set each one's path with `METRICS_PROXY_PATH` or `--metrics_proxy_path`, or build it in the shared file from an environment variable whose value differs per agent, such as the host name a container gets: `proxyPath = ${HOSTNAME}_agent_metrics`. Then add the scrape jobs to your `prometheus.yml`: ```yaml scrape_configs: # Scrape proxy internal metrics - job_name: 'prometheus-proxy' metrics_path: /metrics static_configs: - targets: ['proxy-host.example.com:8082'] # Scrape each agent's internal metrics through the proxy, one job per agent. The agent # serves them at a path of its own (agent.metrics.proxyPath, cluster_a_agent_metrics here). - job_name: 'agent-cluster-a' metrics_path: /cluster_a_agent_metrics static_configs: - targets: ['proxy-host.example.com:8080'] ``` Before 4.7.0, an agent served them only on its metrics port, so it scraped that port through a separate path. That still works, and suits an agent whose port is on for another reason (see [Port or Proxy Path](#port-or-proxy-path)): ```hocon agent { metrics.enabled = true pathConfigs: [ // ... the agent's targets, plus its own metrics, from its own port: { name: "Agent metrics", path: cluster_a_agent_metrics, url: "http://localhost:8083/metrics" } ] } ``` An [embedded agent](https://prometheus-proxy.com/embedded-agent/index.md) sets the path with its builder's `agentMetricsAt(path)`, or with the `metrics-proxy-path` property of the [Spring Boot Starter](https://prometheus-proxy.com/spring-boot-starter/index.md) or the [Ktor Plugin](https://prometheus-proxy.com/ktor-plugin/index.md). It serves its `agent_*` series there, and leaves the JVM's metrics to the app's path (see [Agent's Metrics](https://prometheus-proxy.com/embedded-agent/index.md#the-agents-own-metrics)). ### Port or Proxy Path An agent serves its metrics on its metrics port, at its proxy path, or both: | | Metrics port | Proxy path | |:-------------------------|:-----------------------------------------------------------------------------------------------|:--------------------------------------------------------------------------------------------| | Turned on by | `agent.metrics.enabled`, `--metrics`, `METRICS_ENABLED` | `agent.metrics.proxyPath`, `--metrics_proxy_path`, `METRICS_PROXY_PATH` | | Read | At `http://agent-host:8083/metrics`, by whatever can reach the agent's host | Through the proxy, as the agent's targets are, while the agent is connected | | Opens a port | Yes | No | | A standalone agent's | Its `agent_*` metrics, and the [JVM metrics](#jvm-metrics) its `agent.metrics` settings turn on | The same | | An embedded agent's | Everything in its JVM's default registry, the app's metrics too, when they're kept there | Its `agent_*` series alone: the app's path carries the JVM's | Prometheus, outside the firewall, can read only the proxy path, so an agent that serves its metrics only to it needs no port, as the [Plain Kotlin Demo](https://prometheus-proxy.com/plain-kotlin-demo/index.md#its-metrics-and-its-agents)'s agents do. The port is for something inside the firewall: - **A scraper on the agent's network,** such as a Prometheus, Grafana Alloy, or an OpenTelemetry Collector there, which reads the agent whether or not it reaches the proxy. - **An agent that can't reach the proxy.** What the proxy serves of an agent stops when the agent's link does: an agent that never connects, for a wrong endpoint, token, or certificate, one whose registration fails, and every agent while the proxy, or the network between, is down. Prometheus then sees only the path go: its job's `up` goes to 0, and `agent_connected` can't report 0 (see [Agent Metrics](#agent-metrics)). The agent keeps counting, `agent_connect_count_total{type="failure"}` among them, but nothing outside reads it until it reconnects; a scraper inside reads it throughout. Without such a scraper, leave the port off: nothing outside the firewall can reach it, and the proxy's own metrics and [dashboard](https://prometheus-proxy.com/web-dashboard/index.md), and the job's `up`, report an agent that's gone. Both can be on at once, serving the same series, so have each scraper read one of them. ### JVM Metrics Both components support optional JVM metrics: ```hocon proxy.metrics { enabled = true // Optional JVM metrics standardExportsEnabled = true memoryPoolsExportsEnabled = true garbageCollectorExportsEnabled = true threadExportsEnabled = true classLoadingExportsEnabled = false versionInfoExportsEnabled = false bufferPoolExportsEnabled = true compilationExportsEnabled = true nativeMemoryExportsEnabled = false // Needs the JVM's Native Memory Tracking; see below } ``` The same options are available under `agent.metrics`. An agent serves the groups they turn on on its metrics port, and a standalone agent at its proxy path too, with the port off or on (see [Port or Proxy Path](#port-or-proxy-path)). An embedded agent's JVM metrics are its app's, so with its port off the options do nothing. The JVM metrics come from the Prometheus Java client 1.x. Since the move to it, the memory metrics put the unit last (`jvm_memory_used_bytes`, not `jvm_memory_bytes_used`; `jvm_memory_pool_used_bytes`, not `jvm_memory_pool_bytes_used`; the same for `committed`, `max` and `init`), `jvm_info` is `jvm_runtime_info`, and `memoryPoolsExportsEnabled` also adds `jvm_memory_pool_allocated_bytes_total`. Since 4.3.0, three more groups are available, also off by default: - `bufferPoolExportsEnabled` adds `jvm_buffer_pool_used_bytes`, `jvm_buffer_pool_capacity_bytes` and `jvm_buffer_pool_used_buffers`, by `pool` (`direct` and `mapped`): the memory the JVM's NIO buffer pools hold outside the heap. - `compilationExportsEnabled` adds `jvm_compilation_time_seconds_total`, the time the JIT compiler has spent. - `nativeMemoryExportsEnabled` adds `jvm_native_memory_reserved_bytes` and `jvm_native_memory_committed_bytes`, by `pool`. It reads the JVM's Native Memory Tracking, which is off unless the JVM starts with `-XX:NativeMemoryTracking=summary` (for the Docker images, set `JAVA_TOOL_OPTIONS=-XX:NativeMemoryTracking=summary`). Without it the flag exports nothing, and tracking adds some overhead. ## Proxy Metrics ### Counters | Metric | Labels | Description | |:------------------------------------------|:----------|:----------------------------------------------------------------| | `proxy_scrape_requests_total` | `type` | Scrape request outcomes (see below) | | `proxy_connect_count_total` | — | Agent connects the proxy accepted | | `proxy_agent_connect_refusals_total` | `reason` | Agent connects refused (see below) | | `proxy_agent_disconnects_total` | `reason` | Agents the proxy removed: `eviction`, `termination`, `stream_terminated`, `replaced` | | `proxy_eviction_count_total` | — | Stale agent evictions | | `proxy_heartbeat_count_total` | — | Heartbeats the proxy accepted | | `proxy_agent_auth_failures_total` | `reason` | Agent calls refused for their token: `missing_token`, `unknown_token` | | `proxy_path_rejections_total` | `cause` | Path registrations refused, by cause (see below) | | `proxy_binding_mismatches_total` | `rpc` | Agent calls naming another agent or identity than their connection's | | `proxy_late_scrape_results_total` | — | Scrape results that arrived after their scrape had ended | | `proxy_chunk_validation_failures_total` | `stage` | Chunk integrity failures (`chunk` or `summary`) | | `proxy_chunked_transfers_abandoned_total` | — | Chunked transfers whose scrape ended before they finished | | `proxy_agent_displacement_total` | — | Path registrations that displaced another agent | | `proxy_dashboard_logins_total` | `outcome` | Dashboard logins: `success`, `failure`, `blocked` | **`proxy_scrape_requests_total` type labels:** | Value | Meaning | |:------------------------|:---------------------------------------------------------------------| | `success` | Scrape completed successfully | | `timed_out` | Agent did not answer within the proxy's `scrapeRequestTimeoutSecs` | | `upstream_timed_out` | The agent's fetch timed out, or the target answered 408 or 504 | | `invalid_path` | No agent has registered the requested path | | `missing_path` | The request had no path (a scrape of `/`) | | `agent_disconnected` | Agent disconnected, evicted, or displaced before answering (503) | | `agent_backlog_full` | Agent's queue was full (2 × `scrapeRequestBacklogUnhealthySize`) | | `proxy_in_flight_limit` | In-flight scrapes across agents hit `maxInFlightScrapeRequests` | | `client_cancelled` | Prometheus hung up before the agent answered | | `missing_results` | Internal error: results object was null | | `path_not_found` | The agent doesn't serve the path, or the target answered 404 | | `upstream_error` | Any other non-2xx from the target, or an unreachable target (503) | | `invalid_response` | Agent answered, but a chunk failed validation or its status can't be served (502) | | `content_too_large` | Over the agent's content-length limit, or the target answered 413 | | `payload_too_large` | Unzipped content exceeded the proxy's size limit | | `invalid_gzip` | Gzip decompression failed | | `proxy_stopped` | Proxy is shutting down (503) | | `invalid_agent_context` | All agents for the path are in an invalid state | | `internal_error` | The scrape threw, and the client got a 500 | **Agents and paths the proxy refused:** - `proxy_agent_connect_refusals_total`'s `reason` is `identity_limit`, a connect past `proxy.internal.maxAgentsPerIdentity` (with `transportFilterDisabled`), or `transport_filter_mismatch`, an agent and proxy that disagree on `transportFilterDisabled`. A refused connect isn't in `proxy_connect_count_total`. - `proxy_path_rejections_total`'s `cause` is the reason the agent is told, lowercased: `held_by_another_identity`, `consolidation_mismatch`, `not_authorized`, `invalid_path`, `invalid_agent`, `binding_mismatch`, `path_limit_reached`, or `held_by_another_agent`, a displaced agent's attempt to take back a path another agent still serves, which it repeats until that agent leaves. Every rejection counts, retries included, while the dashboard's Activity view shows a path's first, and leaves out `held_by_another_agent`, which the path's `taken over` line already explains. - `proxy_agent_auth_failures_total` counts every refused call, though the proxy's warning about a host's bad token is logged at most once a minute. An agent with a wrong token reconnects every few seconds, so it climbs steadily. - `proxy_binding_mismatches_total` stays at zero for the stock agent. Its `rpc` label names the call, such as `registerPath` or `writeResponsesToProxy`. Each of these counters exposes every value of its label at zero from the start, so `increase()` and `rate()`, and an alert built on them, see the first event rather than only a second one. **Agents that leave:** `proxy_agent_disconnects_total` counts each agent the proxy removes, by why: `eviction` (no contact within [`maxAgentInactivitySecs`](https://prometheus-proxy.com/configuration/proxy/index.md#internal-settings), also in `proxy_eviction_count_total`), `termination` (its connection closed), `stream_terminated` (its scrape stream ended, with `transportFilterDisabled`), or `replaced` (the agent reconnected before the proxy saw its old connection close, and its new one took the old one's last path). A connection that never authenticated, such as a port probe, isn't counted. **Late and abandoned results:** a result that arrives after its scrape ended, usually at Prometheus's or the proxy's timeout, counts in `proxy_late_scrape_results_total`. The scrape itself was already counted as `timed_out` or `client_cancelled`. A chunked transfer under way when its scrape ends counts once in `proxy_chunked_transfers_abandoned_total`. !!! tip "Proxy-side and agent-side pairs" `timed_out` means the proxy gave up waiting on the agent; `upstream_timed_out` means the agent answered promptly to report that the *target* was slow. Since `agent.scrapeTimeoutSecs` (15s) is well under the proxy's `scrapeRequestTimeoutSecs` (90s), `upstream_timed_out` is the one you will usually see for a slow endpoint. The agent also stops at Prometheus's `scrape_timeout` when that is shorter. Likewise `content_too_large` is the agent's `maxContentLengthMBytes` limit, or the target's 413, while `payload_too_large` is the proxy's unzip limit. Both surface as HTTP 413. The target's non-2xx status passes through, so each agent-side label is the agent's own condition or the target's same status: `path_not_found` for 404, `upstream_timed_out` for 408 or 504, `content_too_large` for 413, and `upstream_error` for the rest. A target the agent couldn't reach, such as a refused connection, is the agent's own 503 `upstream_error`; the agent's `agent_scrape_request_count_total{type="failure"}` tells those apart. A scrape the proxy fails itself names why instead: `agent_disconnected` (look at the agent's connection, not the target), `proxy_stopped`, or `invalid_response`, an answer it can't use, such as a status outside 200–599, or a 204, 205, or 304. ### Histograms | Metric | Labels | Description | |:---------------------------------------|:-------------------|:--------------------------------------------------------------| | `proxy_scrape_request_latency_seconds` | `path`, `outcome` | End-to-end scrape latency | | `proxy_scrape_queue_wait_seconds` | — | Time a scrape waited before the agent's stream took it | | `proxy_scrape_response_bytes` | `path`, `encoding` | Response payload size after decompression | | `proxy_agent_connection_duration_seconds` | `reason` | How long each agent the proxy removed was connected | A path's series are removed when its last registration goes away, whether it is unregistered or its agent disconnects, so a retired path stops appearing on `/metrics`. A scrape still in flight when that happens is not recorded, so it cannot bring the series back. The latency histogram's `outcome` label takes the `proxy_scrape_requests_total` `type` values above, so latency can be split by result. `proxy_scrape_queue_wait_seconds` is the part of the end-to-end latency spent waiting behind the agent's other scrapes. When the latency climbs and the queue wait climbs with it, the agent is busy; when the queue wait stays low, the time is in the network or the target. Like the latency histogram, it leaves out the dashboard's Scrape now. Latency buckets: 5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s, 2.5s, 5s, 10s, 15s, 30s, 60s, 90s The queue wait histogram has the same buckets. Response size buckets: 1KB, 10KB, 100KB, 500KB, 1MB, 5MB, 10MB `proxy_agent_connection_duration_seconds` is observed as `proxy_agent_disconnects_total` counts, with the same `reason`, from the agent's connect to its removal, so connections that end young, closing within seconds or minutes of connecting, point at a flaky link or an agent that keeps restarting. Its buckets are 5s, 15s, 30s, 1m, 90s, 2m, 5m, 10m, 30m, 1h, 4h, 1d, and 1w. ### Gauges | Metric | Description | |:--------------------------------------|:---------------------------------------------------------------------| | `proxy_start_time_seconds` | Proxy start time (Unix epoch), by `launch_id` | | `proxy_build_info` | Always 1, by `launch_id` and `version` | | `proxy_agent_map_size` | Number of connected agents | | `proxy_path_map_size` | Number of registered scrape paths | | `proxy_scrape_map_size` | Number of in-flight scrape requests | | `proxy_chunk_context_map_size` | Number of in-flight chunked transfers | | `proxy_cumulative_agent_backlog_size` | Total queued scrape requests across all agents | | `proxy_dashboard_sessions` | Dashboard pages open | | `proxy_agent_screens_bytes` | Estimated memory the relayed agent dashboards' states hold, in bytes | | `proxy_agent_screens_max_bytes` | `proxy.dashboard.agentScreensMaxMBytes`, in bytes | | `proxy_tls_cert_expiry_timestamp_seconds` | When the first certificate in each TLS collection expires (Unix epoch), by `material`: `cert`, `trust` | | `proxy_identity_paths` | The paths each auth identity's agents serve together, by `identity` | | `proxy_identity_agents` | The connected agents of each auth identity, by `identity` | | `proxy_agent_paths_max` | The paths of the agent that serves the most | | `proxy_limit` | Each limit on what agents hold, by `setting`: `maxPathsPerAgent`, `maxPathsPerIdentity`, `maxAgentsPerIdentity` (0 unless `transportFilterDisabled`); 0 is none | | `proxy_consolidated_path_agents` | The agents serving each consolidated path, by `path` | | `proxy_agent_screens_partial` | Relayed agent dashboards shown in part, by `reason`: `too_large`, `total_full`, `resending` | `proxy_tls_cert_expiry_timestamp_seconds` has a series for each TLS collection the proxy was given: `cert`, its certificate chain, and with mutual TLS `trust`, the collection it checks agents' certificates against, so with TLS off it has none. Each is the earliest NotAfter among the collection's certificates, so an intermediate that expires before the proxy's own certificate counts. `ProxyTlsCertExpiringSoon` in the [alerting rules](https://prometheus-proxy.com/grafana/index.md#alerting-rules) warns 14 days ahead. **Limits on what agents hold:** `proxy_limit` gives each [`proxy.internal`](https://prometheus-proxy.com/configuration/proxy/index.md#internal-settings) limit as the proxy enforces it, every one always, so a panel or an alert can set a count against it: `proxy_identity_paths` against `maxPathsPerIdentity`, `proxy_agent_paths_max` against `maxPathsPerAgent`, and `proxy_identity_agents` against `maxAgentsPerIdentity`. That one applies only with `transportFilterDisabled`, so its series is 0 unless the transport filter is disabled. An identity is the `proxy.auth` entry an agent's token names; agents with no auth identity, as with agent auth off, are `none`, and those on the legacy `proxy.agentToken` `legacy-agent-token`. An identity with no paths or agents has no series. In the [alerting rules](https://prometheus-proxy.com/grafana/index.md#alerting-rules), `ProxyIdentityNearPathLimit`, `ProxyAgentNearPathLimit`, and `ProxyIdentityNearAgentLimit` warn past 80% of each limit, unless it's 0. **Consolidated paths:** `proxy_consolidated_path_agents` has a series for each [consolidated](https://prometheus-proxy.com/advanced/index.md#consolidated-mode) path, the number of agents serving it; an exclusive path has none. A path at 1 has lost its redundancy, or never had it: `consolidated` covers every path an agent registers, so a consolidated agent's own metrics path (`agent.metrics.proxyPath`), named for that agent alone, stays at 1. One whose last agent leaves is unregistered, so its series goes. `proxy_agent_screens_bytes` is the proxy's estimate of the memory it holds for the [relayed agent dashboards](https://prometheus-proxy.com/screens-page/index.md) on its screens page, and `proxy_agent_screens_max_bytes` the most they may hold together. Both are 0 with `proxy.dashboard.agentScreens` off. At the limit, the proxy lets go of gone agents' states and shows the rest in part, so a total that stays at it is a reason to raise `agentScreensMaxMBytes`, with the heap. `proxy_agent_screens_partial` counts the agents' dashboards the proxy shows in part, by `reason`: `too_large`, an agent's state larger than the proxy keeps of one; `total_full`, the room for every agent's state full; `resending`, an agent sending its whole state again, shown as it comes until it ends. Each is 0 with agent screens off. `proxy_dashboard_logins_total` counts a sign-in on the login page as `success`, a wrong login, from the page or a script's Basic Auth, as `failure`, and a login refused because its address made too many wrong ones as `blocked`. A script's right Basic Auth logs in on every request, so it isn't counted. ## Agent Metrics ### Counters | Metric | Labels | Description | |:-----------------------------------|:--------------------|:----------------------------------------------------------------------------------------------| | `agent_scrape_request_count_total` | `launch_id`, `type` | Scrape requests processed (`success`, `unsuccessful`, `timed_out`, `failure`, `invalid_path`) | | `agent_scrape_result_count_total` | `launch_id`, `type` | Results sent (`non-gzipped`, `gzipped`, `chunked`, `dropped`) | | `agent_connect_count_total` | `launch_id`, `type` | Connection attempts (`success`, `failure`, `rejected`) | | `agent_disconnects_total` | `launch_id` | Registered connections to the proxy that ended | | `agent_endpoint_advances_total` | `launch_id` | Moves to the next proxy endpoint after a failed connect or a rejected registration | | `agent_heartbeats_total` | `launch_id`, `outcome` | Heartbeats sent (`success`, `evicted`, `transient_failure`) | | `agent_path_rejections_total` | `launch_id`, `cause` | Path registrations the proxy refused, by the cause it gave | | `agent_discovery_reconciles_total` | `launch_id`, `outcome` | Path discovery reconciles (`success`, `failure`) | | `agent_scrape_retries_total` | `launch_id` | Retries of a target's request, under `agent.scrapeMaxRetries` | | `agent_filter_lines_dropped_total` | `launch_id`, `path` | Lines removed by the path's metric filter | | `agent_filter_bytes_saved_total` | `launch_id`, `path` | Bytes saved before gzip by the metric filter | | `agent_filter_fail_open_total` | `launch_id`, `path`, `reason` | Scrapes the filter passed through unfiltered (`non_text`, `invalid_utf8`) | | `agent_dashboard_scrapes_total` | `launch_id` | Scrapes the proxy's dashboard asked for, which the `agent_scrape_*` metrics leave out | | `agent_dashboard_logins_total` | `launch_id`, `outcome` | The direct agent dashboard's logins (`success`, `failure`, `blocked`) | | `agent_path_takeovers_total` | `launch_id` | Paths the proxy said another agent took over | | `agent_dashboard_relay_failures_total` | `launch_id` | Failures of the relay to the proxy's screens page, each retried while connected | The `launch_id` label identifies each agent instance: an agent gets a new one each time it starts, and each of several agents embedded in one JVM has a different one. `unsuccessful` means the target answered with a non-2xx status or a response over `agent.http.maxContentLengthMBytes`; `timed_out` means the target didn't answer within the agent's scrape timeout; `failure` means the fetch failed without an answer, such as a refused connection or a DNS failure; `invalid_path` means the proxy asked for a path the agent doesn't serve. A result counts as sent once gRPC takes it to send, and as `dropped` when the connection to the proxy closes first. A connect counts as `success` once the proxy has registered the agent, as `rejected` when the proxy refuses the registration, and as `failure` when it can't be made or registered. `agent_disconnects_total` counts each registered connection that ends, however it ends, unless the agent is stopping, and `agent_endpoint_advances_total` each move to the next endpoint in `agent.proxy.endpoints` after a failed connect or a rejected registration; a return to the primary shows as `agent_proxy_endpoint_index` going back to 0. A heartbeat is `evicted` when the proxy no longer knows the agent. `agent_path_rejections_total` counts every refusal, retries included, while the agent's dashboard and log show a path's first; its `cause` is the cause the proxy gave, lowercased, or `unspecified` from a proxy that predates it. `agent_path_takeovers_total` counts each path the proxy said another agent [took over](https://prometheus-proxy.com/glossary/index.md#takeover) once, as the agent's log and dashboard report it, and not each time the proxy names the holder again. `agent_dashboard_relay_failures_total` counts each failure of the relay that shows the agent's dashboard on the proxy's [screens page](https://prometheus-proxy.com/screens-page/index.md#agent-screens), the repeats the agent logs at DEBUG included, but not the relay's end as the connection ends. `agent_discovery_reconciles_total` counts each poll of the discovery file, a failure keeping the paths read last, and `agent_filter_fail_open_total` each scrape a filter let through unfiltered, which the agent logs only the first time. The connection's counters, the heartbeats', the path rejections', the takeovers', and the retries' expose each value of their labels at zero from the start, and discovery's, the dashboard's logins', and the relay's failures' do on an agent that has them (the relay's with `agent.dashboard.showOnProxy` on), so `increase()` and `rate()` see the first event. The `agent_scrape_*` counters and latency histogram count only Prometheus's scrapes. A [scrape from the dashboard](https://prometheus-proxy.com/web-dashboard/index.md#scrape-now) counts in `agent_dashboard_scrapes_total` instead, whatever its outcome, which the dashboard shows to whoever asked. Neither it nor a [Scrape now](https://prometheus-proxy.com/agent-dashboard/index.md#scrape-now) on the agent's dashboard counts in the `agent_filter_*` counters, and the agent's Scrape now counts in none of these. The three `agent_filter_*` counters only create series for paths that have a filter configured, so they are absent entirely unless [metric filtering](https://prometheus-proxy.com/configuration/agent/index.md#metric-filtering) is in use. See that section for what the filter does and does not drop. ### Histograms | Metric | Labels | Description | |:---------------------------------------|:--------------------------|:-------------------------------------------------------------| | `agent_scrape_request_latency_seconds` | `launch_id`, `agent_name` | Time to fetch from target endpoint | | `agent_scrape_queue_wait_seconds` | `launch_id` | Time a scrape request waited before its scrape started | Both have the proxy latency histogram's buckets, up to 90s, past the agent's 15s scrape timeout. The queue wait is the time a request waited for one of `agent.http.maxConcurrentClients`; it leaves out a dashboard's scrape, as the latency histogram does. ### Gauges | Metric | Labels | Description | |:-------------------------------------------------|:-----------------------------------|:-----------------------------------------------------------| | `agent_start_time_seconds` | `launch_id` | Agent start time (Unix epoch) | | `agent_build_info` | `launch_id`, `agent_name`, `version` | Always 1 | | `agent_connected` | `launch_id` | 1 while connected to a proxy and registered, else 0 | | `agent_proxy_endpoint_index` | `launch_id` | The endpoint in use, by its place in `agent.proxy.endpoints`: 0 is the primary | | `agent_paths` | `launch_id`, `source` | Paths registered with the proxy (`static`, `discovered`) | | `agent_discovery_last_success_timestamp_seconds` | `launch_id` | Path discovery's last successful reconcile (Unix epoch) | | `agent_dashboard_sessions` | `launch_id` | The direct agent dashboard's open pages, with it on | | `agent_scrape_backlog_size` | `launch_id` | Pending scrape requests queued | | `agent_client_cache_size` | `launch_id` | Number of cached HTTP clients | | `agent_tls_cert_expiry_timestamp_seconds` | `launch_id`, `material` | When the first certificate in each TLS collection expires (Unix epoch): `trust`, `cert` | | `agent_paths_waiting` | `launch_id`, `reason` | Paths not registered with the proxy, by why: `taken_over`, `retrying` | | `agent_discovery_skipped_entries` | `launch_id` | Discovery file entries the last read skipped as unusable, with discovery on | | `agent_dashboard_relay_up` | `launch_id` | 1 while the dashboard relay to the proxy's screens page is open, else 0 | | `agent_stuck_sources` | `launch_id` | In-process sources with a call that outlived its scrape's timeout | An agent's metrics reach Prometheus through the proxy unless it scrapes the agent directly, so a disconnected agent can't report `agent_connected` as 0: its job's `up` goes to 0 instead. A scraper on the agent's network can read it from its metrics port throughout (see [Port or Proxy Path](#port-or-proxy-path)). `agent_tls_cert_expiry_timestamp_seconds` has a series for each TLS collection the agent was given: `trust`, the collection it checks the proxy's certificate against, and with mutual TLS `cert`, its own certificate chain, so with TLS off it has none. Each is the earliest NotAfter among the collection's certificates. An agent whose certificate has expired can't connect, so through the proxy it can't report it then: `AgentTlsCertExpiringSoon` warns 14 days ahead. `agent_paths_waiting` reports both reasons for every agent, 0 when no path waits: `taken_over`, a path another agent took over, which the agent takes back once no agent serves it, and `retrying`, a static path waiting for the retry task, or a discovered one for the next reconcile, after a refusal that can clear or a call the proxy never answered. A path refused for a cause that can't clear isn't waiting, and shows as `refused` on the agent's dashboard. The agent that takes a path over usually serves the displaced agent's metrics path too, as a second copy of the agent does, so Prometheus reads the displaced agent's `taken_over` only through its metrics port, or a metrics path the other agent doesn't serve. `AgentPathsWaiting` warns once a path has waited 10 minutes, and `AgentDiscoverySkippedEntries` once the discovery file has kept an unusable entry for 5. `agent_dashboard_relay_up` has a series only while the agent is connected to a proxy that shows it on its [screens page](https://prometheus-proxy.com/screens-page/index.md#agent-screens), so an agent whose proxy has agent screens off reports none, rather than a 0 an alert would read as down. It's 0 for the 5 seconds the relay waits, after a failure or after the proxy ended its streams, before it opens them again. `agent_stuck_sources` has a series only for an agent with a path served [in-process](https://prometheus-proxy.com/embedded-agent/index.md#metrics-served-in-process), and counts each source whose call ignored its scrape's timeout and hasn't returned: the source fails its scrapes until it does. ## Metric Flow ```text Prometheus --- HTTP GET ---> Proxy Agent | | records the start time | | | writeScrapeRequest() | queueWait.observe(age) -- gRPC stream --> fetchScrapeUrl() | agentLatency.startTimer() | | | HTTP GET to target | | | agentLatency.observeDuration() | scrapeRequestCount.inc() | scrapeResultCount.inc() | | assignScrapeResults() <-- gRPC -----------+ | responseBytes.observe() latency.observe(elapsed) scrapeRequestCount.labelValues(outcome).inc() | <-- HTTP response --- ``` ## PromQL Examples ### Scrape Success Rate ```promql # Scrape success rate (last 5 minutes): (sum(rate(proxy_scrape_requests_total{type="success"}[5m])) or vector(0)) / sum(rate(proxy_scrape_requests_total[5m])) * 100 ``` ### P99 Scrape Latency ```promql # P99 scrape latency: histogram_quantile(0.99, sum by (le) (rate(proxy_scrape_request_latency_seconds_bucket[5m])) ) ``` ### P99 Latency per Path ```promql # P99 latency per path: histogram_quantile(0.99, sum by (le, path) (rate(proxy_scrape_request_latency_seconds_bucket[5m])) ) ``` ### Error Rate by Type ```promql # Error rate by type: sum by (type) (rate(proxy_scrape_requests_total{type!="success"}[5m])) ``` ### Agent Latency by Name ```promql # Agent scrape latency by agent name: histogram_quantile(0.99, sum by (le, agent_name) (rate(agent_scrape_request_latency_seconds_bucket[5m])) ) ``` ## Admin Endpoints ```text Admin endpoints (when admin is enabled): Proxy (default port 8092): GET /ping - Returns "pong" (liveness check) GET /healthcheck - Returns health status JSON GET /version - Returns version info GET /threaddump - Returns JVM thread dump GET /debug - Returns proxy debug info (if debug enabled) Agent (default port 8093): GET /ping - Returns "pong" (liveness check) GET /healthcheck - Returns health status JSON GET /version - Returns version info GET /threaddump - Returns JVM thread dump GET /debug - Returns agent debug info (if debug enabled) ``` Enable admin endpoints: ```bash java -jar prometheus-proxy.jar --admin java -jar prometheus-agent.jar --admin ``` ## Grafana Dashboards ```text Importing Grafana dashboards: 1. In Grafana, go to Dashboards > Import 2. Upload the JSON file or paste its contents 3. Open the dashboard and pick your Prometheus datasource in its Datasource drop-down Dashboard files in the repository: grafana/prometheus-proxy.json - Proxy health, throughput, latency, errors grafana/prometheus-agents.json - Agent health, scrape activity, per-agent latency Requirements: - Grafana 10.0 or later - A Prometheus datasource scraping the proxy's and the agents' metrics endpoints, with each agent in its own job ``` ### Proxy Dashboard Key panels to monitor: | Section | What to Watch | |:--------------------------|:---------------------------------------------------------------------------------------------------------------------| | **Overview** | Success rate dropping below 99%, error count spikes, each proxy's version, a TLS certificate near its expiry | | **Throughput** | Sudden changes in request volume or error ratio | | **Latency** | P99 creeping up indicates slow targets or network issues; queue wait climbing with it means a busy agent | | **Payload** | Unexpectedly large responses, gzip vs plain distribution | | **Internal State** | Growing backlog means agents can't keep up; agents heartbeat only when idle, so zero heartbeats is normal under load | | **Paths & Limits** | An identity's paths or agents, or the busiest agent's paths, nearing its limit; a consolidated path down to one agent | | **Errors & Events** | Which error types dominate; agents disconnecting, and why, and connections that end young; refused connects; results arriving after a timeout | | **Security & Rejections** | Agents refused for their token, paths refused and why, any binding mismatch | | **Chunk Health** | Any chunk validation failure or abandoned transfer | | **Dashboard** | Wrong or blocked dashboard logins, how many pages are open, and relayed agent dashboards' memory against its limit, and those shown in part | The **Job** and **Instance** pickers pick out one proxy when Prometheus scrapes more than one, such as a high-availability pair. ### Agents Dashboard Key panels to monitor: | Section | What to Watch | |:--------------------|:--------------------------------------------------------------------------------------| | **Overview** | Unexpected agent count changes; an agent not connected, or on a backup endpoint; each agent's version; a TLS certificate near its expiry, and the agent it's in | | **Connections** | Failure spikes indicate proxy or network issues; a rejected connect is the proxy refusing the agent; an agent scraped through the proxy can't be read while it can't connect, so watch its job's `up` | | **Scrape Activity** | Imbalanced load; unsuccessful scrapes point at a failing target; any `dropped` result; retries; a filter letting scrapes through unfiltered; an in-process source stuck past its scrape's timeout | | **Paths & Discovery** | A path the proxy keeps refusing, by cause; paths waiting, taken over or retrying, and takeovers; a discovery file that fails to read, or has entries the agent skips | | **Latency** | Per-agent latency outliers point to slow targets; queue wait climbing means too few `agent.http.maxConcurrentClients` | | **Agent Internals** | Growing backlog means the agent is falling behind | | **Dashboard** | Wrong or blocked logins to a direct agent dashboard; a relay to the proxy's screens page that's down or failing | Every agent panel keys on `job`, so scrape each agent in a separate job, as in [Scraping Internal Metrics](#scraping-internal-metrics). --- Source: https://prometheus-proxy.com/grafana/ # Grafana & Alerting Ready-to-import Grafana dashboards and Prometheus alerting rules built on the proxy and agent metrics. For the full metric reference and what each panel watches, see [Monitoring](https://prometheus-proxy.com/monitoring/index.md). !!! info "Prerequisite" The proxy's metrics must be enabled (`--metrics` / `METRICS_ENABLED=true`), and a Prometheus datasource must be scraping them and each agent's metrics, each agent in a separate job and through the proxy, at its `agent.metrics.proxyPath` (or a path to its metrics port). See [Scraping Internal Metrics](https://prometheus-proxy.com/monitoring/index.md#scraping-internal-metrics). ## Dashboards Two dashboards ship in the repository: | File | Covers | |:-----|:-------| | [`grafana/prometheus-proxy.json`](https://github.com/pambrose/prometheus-proxy/blob/master/grafana/prometheus-proxy.json) | Proxy health, TLS certificate expiry, throughput, latency and queue wait, payload sizes, internal state, paths and agents against their limits, consolidated paths down to one agent, errors, agent disconnects and connection age, rejected agents and paths, dashboard logins, relayed agent dashboards' memory and those shown in part | | [`grafana/prometheus-agents.json`](https://github.com/pambrose/prometheus-proxy/blob/master/grafana/prometheus-agents.json) | Agent health and versions, TLS certificate expiry, connections and failover, scrape activity and stuck in-process sources, paths and discovery, paths waiting and takeovers, skipped discovery entries, per-agent latency and queue wait, dashboard logins, the dashboard relay | ### Importing In Grafana (10.0+): **Dashboards → Import**, then either upload the JSON file or paste the raw contents. Then open the dashboard and pick your Prometheus datasource in its **Datasource** drop-down; it starts on Grafana's default datasource: ```bash # Proxy dashboard curl -O https://raw.githubusercontent.com/pambrose/prometheus-proxy/4.9.0/grafana/prometheus-proxy.json # Agents dashboard curl -O https://raw.githubusercontent.com/pambrose/prometheus-proxy/4.9.0/grafana/prometheus-agents.json ``` What each dashboard section watches is described under [Grafana Dashboards](https://prometheus-proxy.com/monitoring/index.md#grafana-dashboards). Each dashboard links, at the top, to every dashboard tagged `prometheus-proxy`, which both are, so each opens the other; tag a dashboard of your own `prometheus-proxy` and both link to it. !!! tip "Try them without importing" `make up` in the `demos/basics` directory of a clone of the repository starts Prometheus and Grafana with both dashboards and the alerting rules below already loaded, against a proxy, three agents, and a set of simulated services; `make down` removes it. See the [Basics Demo](https://prometheus-proxy.com/basics-demo/index.md) page. ## Alerting Rules The rules below ship as [`grafana/alerts.yml`](https://github.com/pambrose/prometheus-proxy/blob/master/grafana/alerts.yml) in the repository: add that file to Prometheus' `rule_files`. The thresholds are starting points — tune them to your environment. Each rule is grounded in a metric documented in [Monitoring](https://prometheus-proxy.com/monitoring/index.md), except `ProxyDown`, which uses Prometheus' `up` series and expects the proxy's scrape job to be named `prometheus-proxy`. `AgentConnectFailures` and `AgentDisconnected` are for an agent Prometheus scrapes directly. An agent scraped through the proxy can't be scraped while it isn't connected, so neither rule sees it then: alert on its job's `up{job="agent-cluster-a"} == 0` instead. `ProxyTlsCertExpiringSoon` and `AgentTlsCertExpiringSoon` warn 14 days before a certificate the proxy or an agent uses expires, while the agent can still connect. `ProxyIdentityNearPathLimit`, `ProxyAgentNearPathLimit`, and `ProxyIdentityNearAgentLimit` warn once an identity's paths, the busiest agent's paths, or an identity's agents pass 80% of their [limit](https://prometheus-proxy.com/configuration/proxy/index.md#internal-settings), before the proxy refuses any; a limit of 0, none, never warns. `AgentPathsWaiting` warns once an agent's path has waited 10 minutes to register, taken over by another agent or retrying, naming the reason, and `AgentDiscoverySkippedEntries` once an agent's discovery file has kept an entry it skips for 5. ```yaml # Prometheus alerting rules for the proxy and agent. Load this file from Prometheus' rule_files and tune the # thresholds to your environment. Each rule is built on a metric documented on the website's Monitoring page, except # ProxyDown, which uses Prometheus' own up series; # `promtool check rules grafana/alerts.yml` validates it, and CI runs that check. groups: - name: prometheus-proxy rules: # The rules below need the proxy's metrics, so this one covers the proxy itself going away. The job name is the # one in the documented scrape config; change it if yours differs. - alert: ProxyDown expr: up{job="prometheus-proxy"} == 0 for: 2m labels: { severity: critical } annotations: summary: "Prometheus cannot scrape the proxy at {{ $labels.instance }}" # A proxy has no success series until a scrape succeeds, so vector(0) stands in for it, and one whose every scrape # since it started has failed is at 0%. With no scrapes in the window, there's nothing to divide by, and no alert. - alert: ProxyScrapeSuccessRateLow expr: | (sum(rate(proxy_scrape_requests_total{type="success"}[5m])) or vector(0)) / sum(rate(proxy_scrape_requests_total[5m])) < 0.99 for: 10m labels: { severity: warning } annotations: summary: "Proxy scrape success rate below 99%" - alert: ProxyScrapeLatencyHigh expr: | histogram_quantile(0.99, sum by (le) (rate(proxy_scrape_request_latency_seconds_bucket[5m]))) > 2 for: 10m labels: { severity: warning } annotations: summary: "Proxy P99 scrape latency above 2s" - alert: ProxyNoAgentsConnected expr: proxy_agent_map_size == 0 for: 5m labels: { severity: critical } annotations: summary: "No agents connected to the proxy" - alert: ProxyBacklogGrowing expr: proxy_cumulative_agent_backlog_size > 100 for: 10m labels: { severity: warning } annotations: summary: "Proxy agent scrape backlog is large ({{ $value }} queued)" # Covers both size limits: content_too_large is the agent's maxContentLengthMBytes rejecting # the target response, or the target's own 413; payload_too_large is the proxy's unzipped-size guard. - alert: ProxyPayloadTooLarge expr: rate(proxy_scrape_requests_total{type=~"payload_too_large|content_too_large"}[5m]) > 0 for: 5m labels: { severity: warning } annotations: summary: "Scrapes are being rejected for exceeding the size limit ({{ $labels.type }})" - alert: ProxyFrequentEvictions expr: rate(proxy_eviction_count_total[5m]) > 0 for: 15m labels: { severity: warning } annotations: summary: "Proxy is evicting stale agents repeatedly" # An agent with a wrong or missing token reconnects every few seconds and never appears, so the refused calls are # the only sign of it. - alert: ProxyAgentAuthFailures expr: sum by (reason) (rate(proxy_agent_auth_failures_total[5m])) > 0 for: 10m labels: { severity: warning } annotations: summary: "Proxy is refusing agent calls for their token ({{ $labels.reason }})" # A path an agent keeps asking for and the proxy keeps refusing is a target Prometheus never scrapes. - alert: ProxyPathRejections expr: sum by (cause) (rate(proxy_path_rejections_total[5m])) > 0 for: 15m labels: { severity: warning } annotations: summary: "Proxy keeps refusing path registrations ({{ $labels.cause }})" # Past each limit on what agents hold, the proxy refuses registrations, so these warn while there's room left. A # limit of 0 is none, so it never warns. maxAgentsPerIdentity applies only with transportFilterDisabled, so its # proxy_limit series is 0 unless the transport filter is disabled. - alert: ProxyIdentityNearPathLimit expr: | proxy_identity_paths > on (job, instance) group_left () (0.8 * proxy_limit{setting="maxPathsPerIdentity"} > 0) for: 10m labels: { severity: warning } annotations: summary: "The agents of identity {{ $labels.identity }} serve {{ $value }} paths, over 80% of proxy.internal.maxPathsPerIdentity" - alert: ProxyAgentNearPathLimit expr: | proxy_agent_paths_max > on (job, instance) (0.8 * proxy_limit{setting="maxPathsPerAgent"} > 0) for: 10m labels: { severity: warning } annotations: summary: "An agent serves {{ $value }} paths, over 80% of proxy.internal.maxPathsPerAgent" - alert: ProxyIdentityNearAgentLimit expr: | proxy_identity_agents > on (job, instance) group_left () (0.8 * proxy_limit{setting="maxAgentsPerIdentity"} > 0) for: 10m labels: { severity: warning } annotations: summary: "{{ $value }} agents are connected as identity {{ $labels.identity }}, over 80% of proxy.internal.maxAgentsPerIdentity" # Past its NotAfter, a certificate in the proxy's chain fails every agent's handshake, and one in the collection # it trusts agents by fails each mutual-TLS agent's. The series is the first of each collection's certificates to # expire, so an intermediate that expires before the proxy's own certificate counts. - alert: ProxyTlsCertExpiringSoon expr: proxy_tls_cert_expiry_timestamp_seconds - time() < 14 * 86400 for: 1h labels: { severity: warning } annotations: summary: "Proxy TLS certificate ({{ $labels.material }}) expires in {{ $value | humanizeDuration }}" - name: prometheus-agent rules: # For an agent Prometheus scrapes directly. Scraped through the proxy, an agent that can't connect can't be # scraped either, so this rule doesn't see its failures, and its job's up series goes to 0 instead. - alert: AgentConnectFailures expr: rate(agent_connect_count_total{type="failure"}[5m]) > 0 for: 10m labels: { severity: warning } annotations: summary: "Agent {{ $labels.job }} is failing to connect to the proxy" - alert: AgentBacklogGrowing expr: agent_scrape_backlog_size > 50 for: 10m labels: { severity: warning } annotations: summary: "Agent {{ $labels.job }} scrape backlog is large" # For an agent Prometheus scrapes directly. Scraped through the proxy, a disconnected agent's metrics can't be # read at all, and its job's up series goes to 0 instead. - alert: AgentDisconnected expr: agent_connected == 0 for: 5m labels: { severity: critical } annotations: summary: "Agent {{ $labels.job }} is not connected to a proxy" # Every reconcile failing, the agent keeping the paths it read last: a missing or malformed discovery file. - alert: AgentDiscoveryFailing expr: | sum by (job) (increase(agent_discovery_reconciles_total{outcome="failure"}[15m])) > 0 and sum by (job) (increase(agent_discovery_reconciles_total{outcome="success"}[15m])) == 0 for: 5m labels: { severity: warning } annotations: summary: "Agent {{ $labels.job }} can't read its path discovery file" # Connected through a backup endpoint: the primary proxy, or the agent's link to it, is down. - alert: AgentNotOnPrimary expr: agent_proxy_endpoint_index > 0 for: 30m labels: { severity: warning } annotations: summary: "Agent {{ $labels.job }} has been on a backup proxy endpoint for 30 minutes" # Past its NotAfter, a certificate in the collection the agent trusts the proxy by, or in its own chain with mutual # TLS, fails its handshake, and an agent scraped through the proxy can't report it then, so this warns ahead. - alert: AgentTlsCertExpiringSoon expr: agent_tls_cert_expiry_timestamp_seconds - time() < 14 * 86400 for: 1h labels: { severity: warning } annotations: summary: "Agent {{ $labels.job }} TLS certificate ({{ $labels.material }}) expires in {{ $value | humanizeDuration }}" # A path the agent doesn't serve: another agent took it over, as a second copy of the agent does, or it waits to # be tried again after a refusal that can clear or a call that failed. Prometheus reads a displaced agent's # metrics only through its metrics port, or a metrics path the other agent doesn't serve too. - alert: AgentPathsWaiting expr: agent_paths_waiting > 0 for: 10m labels: { severity: warning } annotations: summary: "Agent {{ $labels.job }} has {{ $value }} paths not registered with the proxy: {{ $labels.reason }}" # Entries of the path discovery file the agent skips, each without a single-segment path or a URL; the file's # other entries still apply. - alert: AgentDiscoverySkippedEntries expr: agent_discovery_skipped_entries > 0 for: 5m labels: { severity: warning } annotations: summary: "Agent {{ $labels.job }} has unusable path discovery entries: {{ $value }}" ``` !!! tip "Detecting restarts" `proxy_start_time_seconds` and `agent_start_time_seconds` carry a `launch_id` that each proxy or agent instance gets when it starts; a change in `launch_id` (or a sudden reset of `*_start_time_seconds`) flags a restart on a dashboard or alert. `proxy_build_info` carries the same `launch_id` and the proxy's `version`, so an upgrade shows as a new version on the proxy dashboard's Version stat, and `agent_build_info` each agent's on the agents dashboard's Versions table. ## Next Steps { #see-also } - [Monitoring](https://prometheus-proxy.com/monitoring/index.md) — full metric reference and PromQL examples - [Running in Production](https://prometheus-proxy.com/production/index.md) — where alerting fits in the operational checklist - [Troubleshooting](https://prometheus-proxy.com/troubleshooting/index.md) — mapping an alerting `type` back to a root cause --- Source: https://prometheus-proxy.com/troubleshooting/ # Troubleshooting A symptom-driven guide to the failures Prometheus Proxy most commonly produces, with how to confirm each cause and how to fix it. ## From the Dashboard { #from-the-dashboard } If the proxy's [dashboard](https://prometheus-proxy.com/web-dashboard/index.md) is on, find what it shows below. If it isn't, start from [First Steps](#first-steps), which need nothing turned on. **The Paths view** gives each path's last status in its Status column, and each earlier failure as a red dot in History. The Agents view's Recent scrapes give the same statuses. | The dashboard shows | See | |---|---| | 404 | [404 Not Found](#404-not-found): the target answered 404 | | 503 | [503 Service Unavailable](#503-service-unavailable) | | 502 | [502 Bad Gateway](#502-bad-gateway) | | 413 | [413 Payload Too Large](#413-payload-too-large) | | 408, 504, or 499 | [408 Request Timeout and Other Timeouts](#scrape-hangs-then-times-out) | | Another red status | [Prometheus Scrape Returns an Error](#prometheus-scrape-returns-an-error): the target's answer | | [`gone`](https://prometheus-proxy.com/glossary/index.md#gone) beside the agent | [Agent Can't Connect to the Proxy](#agent-cant-connect-to-the-proxy): the path's agent left | | No row for the path | [404 Not Found](#404-not-found): no agent has the path | **The Activity view** is the only place that shows what the proxy refused: a refused agent or path never gets a row in the Paths or Agents view. | The dashboard shows | See | |---|---| | `rejected`, with the reason in Detail | [Registration Is Rejected](#registration-is-rejected) | | [`taken over`](https://prometheus-proxy.com/glossary/index.md#takeover) | [An Agent Is Connected but Serves No Paths](#an-agent-is-connected-but-serves-no-paths) | | `bad token` | [`UNAUTHENTICATED: Missing or invalid agent token`](#unauthenticated-missing-or-invalid-agent-token) | | `refused` | [`RESOURCE_EXHAUSTED` When an Agent Connects behind nginx](#resource_exhausted-when-an-agent-connects-behind-nginx) | | `disconnected` or [`evicted`](https://prometheus-proxy.com/glossary/index.md#stale-agent-cleanup), with no `connected` after it | [Agent Can't Connect to the Proxy](#agent-cant-connect-to-the-proxy) | | `disconnected`, then `connected`, every minute | [Agents Reconnect Every Minute behind nginx](#agents-reconnect-every-minute-behind-nginx) | **An agent's [dashboard](https://prometheus-proxy.com/agent-dashboard/index.md)** shows what never reaches the proxy. | The dashboard shows | See | |---|---| | Connection `failing`, with each endpoint's last error | [Agent Can't Connect to the Proxy](#agent-cant-connect-to-the-proxy), or [TLS Handshake Failures](#tls-handshake-failures) | | A path `refused` or `retrying`, with the proxy's reason | [Registration Is Rejected](#registration-is-rejected) | | A path `retrying`, taken over by another agent | [An Agent Is Connected but Serves No Paths](#an-agent-is-connected-but-serves-no-paths) | ## First Steps Start with what changes nothing. None of these restarts the proxy or an agent, so every team's scrapes carry on. 1. **Scrape the path through the proxy**, bypassing Prometheus, with `curl -i http://:8080/`. The HTTP status narrows down the cause; [Prometheus Scrape Returns an Error](#prometheus-scrape-returns-an-error) covers each one. 2. **Read both logs**, the proxy's and the agent's. Each logs the reason for most rejections, at WARN or INFO, and, at startup, a WARN for each setting it doesn't know: `… isn't a setting, so it has no effect`. 3. **Use what's already on:** - **A dashboard:** start [From the Dashboard](#from-the-dashboard). - **The admin endpoints**, on port `8092` on the proxy and `8093` on the agent by default: `curl http://:/ping` answers `pong`, and `/healthcheck` answers with the health checks' JSON. - **The metrics:** whichever `type` of `proxy_scrape_requests_total` is incrementing, such as `timed_out` or `agent_disconnected`, names the failure mode. [Monitoring](https://prometheus-proxy.com/monitoring/index.md#proxy-metrics) says what each means. !!! warning "Turning on the dashboard, admin, or metrics restarts the proxy" The proxy reads whether each is on (`--dashboard`, `--admin`, and `--metrics`, their environment variables, or its config file) only as it starts. On a shared proxy, that restart stops every team's scrapes until each agent has reconnected and registered its paths again. Do it in a window you announce, as an upgrade is ([What a Proxy Restart Interrupts](https://prometheus-proxy.com/upgrading/index.md#what-a-proxy-restart-interrupts)). Turning one on for an agent restarts only that agent, which interrupts only the paths it serves. Better, turn them on ahead of time, as [Running in Production](https://prometheus-proxy.com/production/index.md#pre-flight-checklist) lists, so finding a cause never needs a restart. Set the dashboard's [login](https://prometheus-proxy.com/web-dashboard/index.md#login) first: anyone who can reach its port can read it until you do ([Exposing the Proxy Dashboard](https://prometheus-proxy.com/dashboard-exposure/index.md#exposure)). ## The Proxy or Agent Exits at Startup ### `java.net.BindException: Address already in use` Another process already listens on one of the proxy's ports: the HTTP port Prometheus scrapes (default `8080`), the agent gRPC port (`50051`), or, when they're enabled, the admin (`8092`), metrics (`8082`), or dashboard (`8094`) port. The proxy logs the exception and exits with status 1, so a supervisor's restart policy retries it. An agent does the same when its admin (`8093`), metrics (`8083`), or dashboard (`8095`) port is taken, and an [embedded agent](https://prometheus-proxy.com/embedded-api/index.md#agentstartasyncagent) throws an `IllegalStateException` with the `BindException` as its cause, having released the ports it had opened. - Find what holds the port: `lsof -nP -iTCP:8080 -sTCP:LISTEN` (macOS, Linux) or `ss -ltnp 'sport = :8080'` (Linux). - Stop that process, or move the proxy to a free port with the matching option in the [CLI Reference](https://prometheus-proxy.com/cli-reference/index.md). ??? note "Through 4.2.0" A proxy whose port was taken logged the error and kept running, holding its admin and metrics ports, so no supervisor's restart policy fired. ### `Invalid configuration: …` A setting failed a check at startup. The line names the setting and why it was refused: fix it and start again. A standalone proxy or agent logs this one line and exits with status 1. An [embedded agent](https://prometheus-proxy.com/embedded-api/index.md#agentstartasyncagent) throws a `ConfigLoadException` with the same reason. When the setting came from the app's environment through [`fromEnvironment()`](https://prometheus-proxy.com/embedded-agent/index.md#settings-from-the-environment), the line names the variable too, as in `Invalid configuration: PROMETHEUS_PROXY_CERT, read by fromEnvironment() for agent.tls.trustCertCollectionPem: trustCertCollectionPem is neither PEM text nor the base64 of PEM text`: fix the variable. The proxy refuses to start with: - **A timeout or limit out of range:** a `proxy.http.idleTimeoutSecs` of `0`, or a negative value other than `-1` (`0` never turned the timeout off; `-1` gives the default, 45 seconds; [Proxy Configuration](https://prometheus-proxy.com/configuration/proxy/index.md)), or a negative `proxy.internal.maxTargetUrlLength`, `proxy.internal.maxAgentsPerIdentity`, `proxy.internal.maxPathsPerIdentity`, or `proxy.internal.maxLabelsPerPath`. - **An auth identity it can't use:** a `proxy.auth` identity named `legacy-agent-token`, the name the legacy shared token has, or a path pattern with a `/` after its leading one, such as `team_a/*`, which no path can match ([Security](https://prometheus-proxy.com/security/index.md#per-agent-identities-and-path-authorization)). - **A service discovery address it can't serve:** a `targetPrefix` with a query or fragment, or, with service discovery on, a `proxy.service.discovery.path` of whitespace, `/` alone, or more than one leading slash ([Prometheus Service Discovery](https://prometheus-proxy.com/service-discovery/index.md)). - **A dashboard entry it can't use:** a `proxy.dashboard.links` entry, or an `icon` it doesn't have ([Links](https://prometheus-proxy.com/web-dashboard/index.md#links)), or a `proxy.dashboard.screens` list the screens page can't use, such as a screen whose `url` is empty, as an unset variable leaves it ([Startup Checks](https://prometheus-proxy.com/screens-page/index.md#startup-checks)). The agent refuses to start with: - **A path no scrape can reach:** a `pathConfigs` path with whitespace, a control character, `?`, or `#`, or a `pathConfigs` path or `agent.metrics.proxyPath` of more than one segment, such as `app/metrics` or `//metrics` ([Path Rules](https://prometheus-proxy.com/configuration/agent/index.md#path-rules)). - **A proxy endpoint it can't dial:** one with no host, such as `:50051` or `[]`, or with anything but `:port` after a bracketed IPv6 address, such as `[::1]50051`. Either refuses to start with a TLS certificate, key, or trust collection file it can't read. ??? note "Which release added these" Through 4.4.2, some of these settings ended in an uncaught exception's stack trace instead of the one line. Most of the checks came in 4.5.0. A negative `proxy.internal.maxPathsPerIdentity` or `proxy.internal.maxLabelsPerPath` fails startup from 4.7.0. These fail it from 4.8.0: a `proxy.auth` path pattern with a `/`, the service discovery path, a path of more than one segment, the agent's proxy endpoint, the screens, and a TLS file the proxy or agent can't read, which ended in a stack trace before. ## Agent Can't Connect to the Proxy An agent that can't connect never appears on the proxy's dashboard. Its direct agent dashboard's [Connection view](https://prometheus-proxy.com/agent-dashboard/index.md#the-connection-view) shows each proxy endpoint, in failover order, with the last error the agent got connecting to it, so a proxy that's down, a wrong port, a refused token, and a TLS mismatch each show there, not only in the agent's log. Turn it on with the agent's `--dashboard` and open it on the agent's port, `8095` by default: a [relayed agent dashboard](https://prometheus-proxy.com/screens-page/index.md#agent-screens) comes only through the connection that's failing. Turning it on restarts the agent, but an agent that can't connect serves no path to interrupt. ### Connection Refused / Timeouts on the gRPC Port - Check that the agent's proxy address (`--proxy`, `PROXY_HOSTNAME`, or `agent.proxy.hostname`, with a port when it isn't the default `50051`) reaches the proxy from the agent's host. In Kubernetes, that's usually a `LoadBalancer` Service's host; see [Kubernetes](https://prometheus-proxy.com/kubernetes/index.md#exposing-grpc-to-remote-agents). - Check that a firewall or security group lets the agent connect out to the proxy's gRPC port. - gRPC runs over HTTP/2, so an L7 reverse proxy, load balancer, or ingress in front of the proxy must speak HTTP/2 and gRPC. ### `UNAUTHENTICATED: Missing or invalid agent token` The proxy has an agent token configured and the agent's token is missing or doesn't match. - **Where it shows:** the agent logs it at ERROR, without a stack trace, as `The proxy at refused the agent's token (...)`, or, with no token, `The proxy at requires an agent token, and the agent sends none (...)`, followed by where the token is set. It logs it on its first attempt, again every 10 minutes while it lasts, and again once it has connected in between, as after a failover; its reconnects every few seconds are at DEBUG. It keeps retrying, since a token changed on the proxy can make the rejection go away. The proxy logs `Refused an agent from (UNAUTHENTICATED): it sent an unknown agent token` (or `no agent token`) at WARN, at most once a minute for each host. Its dashboard's Activity view shows a `bad token` row naming the host, and the agent's [Connection view](https://prometheus-proxy.com/agent-dashboard/index.md#the-connection-view) shows the error beside the endpoint. - **Fix:** set the **same** `--agent_token` / `AGENT_TOKEN` on the agent as on the proxy, or, with [per-agent identities](https://prometheus-proxy.com/security/index.md#per-agent-identities-and-path-authorization), the token of the agent's `proxy.auth` identity. An [embedded agent](https://prometheus-proxy.com/embedded-agent/index.md)'s is its builder's `token()`, which `fromEnvironment()` reads from `PROMETHEUS_AGENT_TOKEN`; the agent's own `AGENT_TOKEN`, if the app's environment has one, takes precedence over it. An empty token on the proxy disables the check only when no `proxy.auth` identities are configured. See [Security](https://prometheus-proxy.com/security/index.md#agent-authentication-pre-shared-token). ??? note "Through 4.6.0" The agent logged a WARN with a stack trace on every refused attempt, and the proxy logged no refused token: only its dashboard's Activity view showed one. ## Prometheus Scrape Returns an Error Scrape the path directly with `curl -i` and match the status. A non-2xx status the target answers with passes through to Prometheus. Each cause below gives, in parentheses, the `type` it counts as in `proxy_scrape_requests_total`, which tells apart causes that share a status. A target's status counts as `path_not_found` for a 404, `upstream_timed_out` for a 408 or 504, `content_too_large` for a 413, and `upstream_error` for any other; the agent's own 404, timeout, and size limit count the same way. ### `404 Not Found` The proxy has no usable mapping for that path, or the target answered 404. - **`metrics_path` mismatch** (`invalid_path`, no agent has the path): Prometheus's `metrics_path` must equal the agent's `path` exactly, with a single leading slash: a `path` of `app1_metrics` in the agent is `metrics_path: '/app1_metrics'` in Prometheus. - **Multi-segment path**: a registered `path` containing an embedded `/` is rejected at registration with `Multi-segment path not supported (use a single path segment)`, and scrapes 404. Use a single segment, such as `app_metrics`, not `app/metrics`. The agent refuses such a path itself, as it does one with a second leading slash (`//app_metrics`): a `pathConfigs` entry at startup, and a discovery entry when it reads the file. - **Agent not registered** (`invalid_path`): confirm the agent started cleanly and registered the path, with `proxy_path_map_size` and the agent's log. The dashboard's Paths view has no row for the path, and its Activity view shows a `rejected` row if the proxy refused it. - **Agent gone** (`invalid_agent_context`, every agent on the path has left): the proxy hasn't removed the path yet. That lasts only a moment, as the path's last agent leaves. After it, the scrape counts as `invalid_path`, and the dashboard's Paths view marks the path `gone`. Check `proxy_agent_map_size` and whether the agent is up. - **Target answered 404** (`path_not_found`): the agent reached the target, but the path's `url` names a page the target doesn't serve. Check the `url` in the agent's config. ### `503 Service Unavailable` The path is known but cannot be served right now, or the agent couldn't reach the target. - **Proxy shutting down** (`proxy_stopped`): the proxy is stopping, and answers no more scrapes. - **Agent disconnected** (`agent_disconnected`): the path's agent left before or during the scrape, whether it disconnected, was evicted, or lost the path to another agent. It's expected, and brief, while an agent restarts. Consolidated mode keeps a path answering while one of its agents is down, when each agent scrapes a separate instance of the service; see [Consolidated Mode](https://prometheus-proxy.com/advanced/index.md#consolidated-mode). - **Agent didn't answer in time** (`timed_out`): the proxy waited `proxy.internal.scrapeRequestTimeoutSecs` (90s) for the agent; see [408 Request Timeout and Other Timeouts](#scrape-hangs-then-times-out). - **Agent or proxy busy** (`agent_backlog_full`, `proxy_in_flight_limit`): the agent's queue already holds twice `proxy.internal.scrapeRequestBacklogUnhealthySize` scrapes, or `proxy.internal.maxInFlightScrapeRequests` scrapes are in flight across all agents. See [Performance Tuning](https://prometheus-proxy.com/advanced/index.md#performance-tuning). - **Target unreachable** (`upstream_error`): the agent couldn't connect to the target, as when it is down or its name doesn't resolve, and answered 503 itself. The agent counts these in `agent_scrape_request_count_total{type="failure"}`, and a 503 the target answered with as `unsuccessful`. ### `502 Bad Gateway` - **Target error** (`upstream_error`): the target itself answered 502; check the target. - **Unusable response** (`invalid_response`): the agent answered, but a chunk or summary failed validation, or it reported a status the proxy can't serve: one outside 200–599, or a 204, 205, or 304, which can't carry the body the proxy always sends. Check `proxy_chunk_validation_failures_total` and the proxy log, which names the status. A gzipped result the proxy can't unzip counts as `invalid_gzip`. - **Zipped payload too large** (`invalid_response`): a result sent in chunks passed `proxy.internal.maxZippedContentSizeMBytes` (default `5`) before it was unzipped, and the proxy log says `Zipped content size … exceeds maximum allowed size`. Raise the limit for a target with that much to send. ### `413 Payload Too Large` The scrape body exceeded a configured size limit. - **Agent side:** raise `agent.http.maxContentLengthMBytes` (default `10`). Outcome label `content_too_large`. - **Proxy side:** raise `proxy.internal.maxUnzippedContentSizeMBytes`, the limit on a result's size once it's unzipped, which holds a body the agent sent without gzip too; `0` rejects every result. Outcome label `payload_too_large`. - The two limits are independent, and both answer with a 413: the outcome label tells you which one rejected the scrape. ### `408 Request Timeout` and Other Timeouts { #scrape-hangs-then-times-out } A scrape that hangs ends at the agent's timeout, the proxy's, or Prometheus's, and its status says which. Because the agent's `scrapeTimeoutSecs` (15s) is well below the proxy's `scrapeRequestTimeoutSecs` (90s), a slow target normally ends at the agent's, as a 408. - 408 Request Timeout (`upstream_timed_out`): the agent answered in time, to report that its fetch of the *target* ran out of time: the target is slow, or the agent's connection to it never completed. A 408 or 504 the target answers itself passes through, with the same label. Fix the target, or raise the agent's `scrapeTimeoutSecs` (default `15`), its `clientTimeoutSecs` (default `90`), or both. The agent also stops at Prometheus's `scrape_timeout`, which the proxy forwards in `X-Prometheus-Scrape-Timeout-Seconds`, so raise that too. The agent passes the timeout it enforces on to the target in the same header, so exporters that size their work by it, such as blackbox_exporter, finish within it. - 503 Service Unavailable (`timed_out`): the agent never answered the proxy at all, because it's unresponsive or the link to it is broken. Check the agent is still connected (`proxy_agent_map_size`), and raise `proxy.internal.scrapeRequestTimeoutSecs` only if the agent legitimately needs longer than 90s. - 499 (`client_cancelled`), on the dashboard and in the proxy's metrics only: Prometheus hung up at its `scrape_timeout`, before the agent answered, so no status reached it, and Prometheus records a timeout. A frozen or saturated agent ends this way, and so can a target slower than that timeout. - Any of them can mean the agent is saturated: raise `agent.http.maxConcurrentClients` (default `1`) so scrapes run in parallel, and watch `agent_scrape_backlog_size` and `proxy_cumulative_agent_backlog_size`. See [Performance Tuning](https://prometheus-proxy.com/advanced/index.md#performance-tuning). ## Registration Is Rejected The proxy refuses the path, logs the reason, and tells the agent, whose log and [dashboard](https://prometheus-proxy.com/agent-dashboard/index.md#the-paths-view) show it too. The proxy's Activity view shows the first refusal as a `rejected` row, with the reason in its Detail column; a path waiting to be taken back shows there as `taken over` instead. | Log reason | Cause / fix | |:------------------------------------------------------------|:----------------------------------------------------------------------------| | `Multi-segment path not supported (use a single path segment)` | The `path` contains an embedded `/`. Use one segment. | | `Invalid path: /… ('…' can't appear in a scrape's request path)` | The `path` contains whitespace, a control character, `?`, or `#`, which no scrape can reach. Rename it. | | `Consolidated agent rejected for non-consolidated path` | A [consolidated](https://prometheus-proxy.com/glossary/index.md#consolidated-mode) agent tried to join a path another agent owns non-consolidated. Make **all** agents for the path consolidated, or none. | | `Non-consolidated agent rejected for consolidated path` | A non-consolidated agent tried to join a consolidated path. Make **all** agents for the path consolidated, or none. | | `Agent identity '…' denied registration of path /…` (the agent logs `… is not authorized to register path /…`) | The path matches none of the `paths` patterns of the agent's [`proxy.auth` identity](https://prometheus-proxy.com/security/index.md#per-agent-identities-and-path-authorization). Add a pattern that covers it, or rename the path. | | `Path /… is served by identity '…'; identity '…' cannot take it over` (or `join it`) | A live agent of another identity serves the path. The agent retries, and registers the path once that agent is gone. To move the path, stop the old agent; for both to serve it, give them the same identity and consolidated mode. | | `Path /… is served by agentId … (…), of another launch; agentId … takes it back once that agent leaves` (INFO) | Not a fault. Another agent took the path over, and this one, told so, is waiting to take it back; see [An agent is connected but serves no paths](#an-agent-is-connected-but-serves-no-paths). | | `Path /… is N characters, over proxy.internal.maxPathLength (…)` | Shorten the path, or raise the limit ([Internal Settings](https://prometheus-proxy.com/configuration/proxy/index.md#internal-settings)). | | `Labels for path /… are N bytes, over proxy.internal.maxLabelsSizeBytes (…)` | Trim the path's `labels`, or raise the limit. | | `Path /… has N labels, over proxy.internal.maxLabelsPerPath (…)` | Drop some of the path's `labels`, or raise the limit. | | `Agent … already serves N paths, the proxy.internal.maxPathsPerAgent limit (…); path /… refused` | Spread the paths across more agents, or raise the limit. | | `The agents of identity '…' already serve N paths, the proxy.internal.maxPathsPerIdentity limit (…); path /… refused` (or `with no auth identity`) | The agents that share the identity hold that many paths together; with agent auth off, or only the legacy `agentToken`, that's every agent. Raise the limit, or split the agents across identities. | | `Invalid path: /… is the service discovery path, which the proxy serves itself` | The proxy serves that path itself, as it does `favicon.ico` and, when enabled, the [Blitz verification path](https://prometheus-proxy.com/service-discovery/index.md#labels). Rename it. | See [Consolidated Mode](https://prometheus-proxy.com/advanced/index.md#consolidated-mode) for the all-or-nothing rule. The agent retries the consolidation and identity conflicts, and a path another agent took over, which clear once the agents serving the path leave; it doesn't retry the others while it stays connected. The proxy logs the first rejection of a path for an agent connection at WARN, and an identical repeat at DEBUG, since an agent retries a rejection that can clear, and a lasting conflict would otherwise fill the log. A multi-segment path is logged at ERROR, and a path the agent's identity may not register at WARN, each time, as the agent retries neither. To see every attempt, set `io.prometheus.proxy.ProxyPathManager` to DEBUG. The agent logs its side of the same conflict, so its log shows whether it is still retrying. ### An Agent Is Connected but Serves No Paths Another agent registered the same paths without consolidated mode and took them over: the later registration serves a path, and the agent it displaced stays connected without it. The proxy logs it at INFO: ``` { .text .pp-output title="The proxy's log" } agentId 1 keeps its connection without paths after agentId 2, of another launch, took over /orders_metrics; ... ``` The proxy's dashboard shows a `taken over` row in its Activity view, naming the agent the path came from. The proxy tells the displaced agent, which logs a WARN naming the agent that took the path, and its [dashboard](https://prometheus-proxy.com/agent-dashboard/index.md) shows the path `retrying`, taken over by that agent. It takes the path back once no agent serves it, within seconds, without reconnecting, and never while the other agent does, even after its connection drops and it reconnects. Its `agent_paths_waiting{reason="taken_over"}` gauge counts the paths it waits for, and `agent_path_takeovers_total` each takeover ([Agent Metrics](https://prometheus-proxy.com/monitoring/index.md#agent-metrics)); Prometheus reads them through its metrics port, or a metrics path the other agent doesn't serve too. If the proxy refuses to give the path back for a cause that can't clear, such as an identity no longer allowed it, the agent stops waiting for it, and the dashboard shows it `refused`. An agent left with no static path served, none to retry, and no discovery then reconnects rather than stay connected to a proxy that serves none of its paths; as at any connect, a proxy that refuses every one of its static paths sends it on to the next in `agent.proxy.endpoints`. If both agents should serve the paths, set `agent.consolidated = true` on each. If only one should, remove the paths from the other's config, or stop it. ??? note "With an agent or proxy from 4.6.0 or earlier" The proxy tells the displaced agent only when both are from 4.7.0 or later. Otherwise the displaced agent shows the path as registered, and takes it back only when it reconnects. Through 4.4.2, the proxy disconnected the displaced agent instead, so the two took the paths from each other in turn, each reconnecting every few seconds. ## TLS Handshake Failures - **Untrusted certificate**: the side validating the certificate needs the CA that signed it in its `trustCertCollectionFilePath`. - **Host name not in the certificate**: the certificate's SAN must match the host name the agent dials, or the agent must set `tls.overrideAuthority` to a name it does carry, as the test fixtures set `foo.test.google.fr`. - **Mutual TLS**: the **agent** must also present a certificate and key, with `certChainFilePath` and `privateKeyFilePath`, and the proxy must trust the CA that signed it. The proxy rejects an agent configured for server-only TLS. - For HTTPS **scrape targets** signed by a private CA, point the agent at `--https_truststore` rather than disabling validation with `--trust_all_x509`. See [TLS Setup](https://prometheus-proxy.com/security/tls/index.md) and the [example configs](https://prometheus-proxy.com/examples/index.md). ## Metrics or Admin Endpoints Don't Answer The endpoints are **disabled by default**, so their ports refuse connections until you enable them with `--admin` / `--metrics` (or `ADMIN_ENABLED=true` / `METRICS_ENABLED=true`). Enabling one restarts the process, and on the proxy, that interrupts every team's scrapes ([What a Proxy Restart Interrupts](https://prometheus-proxy.com/upgrading/index.md#what-a-proxy-restart-interrupts)). A 404 means the port is up but serves no such path: scrape `/metrics` on the metrics port (`8082` proxy, `8083` agent), and `/ping`, `/healthcheck`, `/version`, and `/threaddump` on the admin port (`8092` proxy, `8093` agent). An agent's metrics at a proxy path (`agent.metrics.proxyPath`, or an embedded agent's `agentMetricsAt(path)`) open no port: scrape them through the proxy, at `http://:8080/`, which answers only while the agent is connected and has registered the path. A 404 there means it hasn't; the agent's startup log names the path, and [Port or Proxy Path](https://prometheus-proxy.com/monitoring/index.md#port-or-proxy-path) says when the port suits instead. ## Disconnects Aren't Detected behind nginx With `transportFilterDisabled` (required when fronting gRPC with nginx), the proxy notices an agent leave when the agent's request stream ends, which a disconnect normally does at once. An agent that dies before opening that stream, or whose connection stays half-open, stays listed until [`proxy.internal.maxAgentInactivitySecs`](https://prometheus-proxy.com/configuration/proxy/index.md#internal-settings) (default 60s) evicts it. This is expected; see [nginx Reverse Proxy](https://prometheus-proxy.com/advanced/index.md#nginx-reverse-proxy). ### Agents Reconnect Every Minute behind nginx The agent logs `RST_STREAM closed stream` on `writeChunkedResponsesToProxy()` or `writeResponsesToProxy()`, or `HTTP status code 504` on `readRequestsFromProxy()` or `readPathNoticesFromProxy()`, then `Disconnected from proxy`, about a minute after it connects, and again every minute, scraped or not. Its paths are gone from the proxy for a moment each time, so a scrape can fail. - **Cause:** nginx closes a gRPC stream that's quiet for 60 seconds, and an agent's stream for chunked results carries nothing while its results are small, and its other streams nothing between scrapes. A current agent and proxy keep their streams open with keepalives, but only when both support them, so this happens when the agent or the proxy is from 4.6.0 or earlier, or when a reverse proxy's idle timeout is under `proxy.internal.streamKeepAliveSecs`. - **Fix:** upgrade both, or raise `grpc_read_timeout` and `client_body_timeout` to a day or more; under a shorter idle timeout, lower `streamKeepAliveSecs` below it. See [nginx Reverse Proxy](https://prometheus-proxy.com/advanced/index.md#nginx-reverse-proxy). ### Agents Reconnect with HTTP Status 413 behind nginx The agent logs `writeResponsesToProxy(): UNKNOWN HTTP status code 413`, then `Disconnected from proxy`, and reconnects at once, again and again at an even pace, hours apart for small results, minutes apart for large ones. nginx's error log says `client intended to send too large chunked body`. - **Cause:** nginx counts all an agent sends on a stream as one request body, and an agent's streams of scrape results stay open while it's connected, so nginx ends one with 413 once its results pass `client_max_body_size`, 1 MB by default. Every agent is affected, whatever its version. - **Fix:** set `client_max_body_size 0;` in the `server` or `location` block that passes to the proxy, which turns the limit off. See [nginx Reverse Proxy](https://prometheus-proxy.com/advanced/index.md#nginx-reverse-proxy). ### A Change to nginx Doesn't Reach Connected Agents After `nginx -s reload`, agents connected before it behave as before, and nginx's process list shows workers `shutting down` that never exit. - **Cause:** a reload leaves each open connection with the old worker it's on, under the old config, until the connection ends, and an agent's connection, which its keepalives keep open, doesn't. - **Fix:** set `worker_shutdown_timeout` in nginx's main context and restart nginx once; from then on, each reload hands the agents to the new workers that long after it. See [nginx Reverse Proxy](https://prometheus-proxy.com/advanced/index.md#nginx-reverse-proxy). ### `RESOURCE_EXHAUSTED` When an Agent Connects behind nginx With `transportFilterDisabled`, the proxy refuses a connect once `proxy.internal.maxAgentsPerIdentity` (10,000) agents are connected with the same auth identity, and logs `Refused a connect`. With agent auth off, or on the legacy `proxy.agentToken`, every agent shares one identity, so the limit counts the whole fleet. The agent keeps retrying, and gets in once another agent leaves. - **Fix:** raise the limit, or set it to `0` for none, if the fleet needs more. If it shouldn't, look for agents that keep reconnecting, such as ones whose registration is rejected: each attempt counts until it is evicted. Giving each team a separate `proxy.auth` identity also keeps one team's agents from using up another's room. See [Transport Filter](https://prometheus-proxy.com/configuration/proxy/index.md#transport-filter). ## The Dashboard behind a Reverse Proxy Stays on `reconnecting…` The page loads, but its live indicator never turns green, and Scrape now may say `Origin not allowed`. With a login, the login form says it instead, and the page never loads. - **Cause:** the reverse proxy doesn't pass the WebSocket handshake's `Upgrade` and `Connection` headers, or passes a `Host` header that doesn't match the browser's `Origin`, which the dashboard refuses. Or `allowedOrigins` lists the address with another scheme than the browser's, such as `https://` for a page opened over `http`. - **Fix:** pass both headers, over HTTP/1.1, and the browser's `Host`, or list the dashboard's public address, with the scheme the browser uses, in `proxy.dashboard.allowedOrigins`; see [Behind a reverse proxy](https://prometheus-proxy.com/dashboard-exposure/index.md#behind-a-reverse-proxy). ## Still Stuck? - Check what each metric means in [Monitoring](https://prometheus-proxy.com/monitoring/index.md). - Confirm an option's name in the [CLI Reference](https://prometheus-proxy.com/cli-reference/index.md), and which setting wins: an option overrides an environment variable, which overrides the config file, which overrides the built-in default. - File an issue at [github.com/pambrose/prometheus-proxy/issues](https://github.com/pambrose/prometheus-proxy/issues) with the proxy's and the agent's logs and the direct `curl -i` output. --- Source: https://prometheus-proxy.com/embed/ # JVM Embed For developers whose app runs on the JVM: the agent can run inside the app instead of as a separate process. It reads the app's metrics registry in-process, so the app needs no `/metrics` endpoint and no port for the agent to scrape. Set it up in code, or let the Ktor plugin or the Spring Boot starter start it with the app. ## You Need a Proxy The agent connects out to a proxy, and Prometheus scrapes the proxy, so start a proxy first. Each guide below tells the agent where it is with a `proxy` setting, which its examples read from `PROMETHEUS_PROXY`.
- [Start a proxy on your machine](https://prometheus-proxy.com/getting-started/index.md#installation) The Quick Start's steps 1 and 2, Install and Start the Proxy, with a JAR, Homebrew, or Docker. Stop once the proxy is running and come back here: your app's agent takes the place of step 3's. The proxy takes agents on port 50051 and Prometheus's scrapes on 8080, so an app on the same machine sets `PROMETHEUS_PROXY` to `localhost:50051`. - [Run a proxy in a container](https://prometheus-proxy.com/docker/index.md#production-setup) The proxy's Docker image, with TLS and an agent token, which the agent then needs too. - [Run a proxy for an app on a cloud platform](https://prometheus-proxy.com/cloud-platforms/index.md#where-to-run-the-proxy) A proxy beside Prometheus on AWS, GCP, Azure, DigitalOcean, or Railway, for an app on ECS, Cloud Run, or Azure Container Apps.
## Guides
- [Embedded Agent](https://prometheus-proxy.com/embedded-agent/index.md) When to embed the agent, and how: in code with `embeddedAgent { }`, or from a config file, serving the app's metrics registry in-process. - [Ktor Plugin](https://prometheus-proxy.com/ktor-plugin/index.md) `install(PrometheusProxyAgent)` starts the agent with a Ktor app, stops it with the app, and serves the app's metrics registry. - [Spring Boot Starter](https://prometheus-proxy.com/spring-boot-starter/index.md) A dependency and a few properties start the agent with a Spring Boot app, serve its metrics, and report the agent's connection in Actuator's health.
## API, Debugging, and Upgrading
- [Embedded Agent API](https://prometheus-proxy.com/embedded-api/index.md) The methods and types an app that embeds the agent calls, with what each takes, returns, and throws. - [Debugging an Embedded Agent](https://prometheus-proxy.com/embedded-debugging/index.md) Where the agent logs, its admin and debug endpoints, its dashboard, and the proxy's view of it. - [Upgrading an Embedded Agent](https://prometheus-proxy.com/embedded-upgrading/index.md) What each release since 4.0 changed for code that embeds the agent, and what to do about it.
## Demos Each runs on your laptop with `make up`, in Docker, with a guided tour.
- [Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md) A coffee shop, a Ktor app that runs the agent in-process through the Ktor plugin. - [Spring Boot Demo](https://prometheus-proxy.com/spring-boot-demo/index.md) A roastery, a Spring Boot app in Java whose agent the starter starts from properties. - [Plain Kotlin Demo](https://prometheus-proxy.com/plain-kotlin-demo/index.md) A bakery's ovens: workers with no framework or HTTP server, each running the agent from a few lines of its `main`.
--- Source: https://prometheus-proxy.com/embedded-agent/ # Embedded Agent A JVM app can run the agent inside itself instead of beside it, as a separate process. The agent then connects out to the proxy from within the app, and can read the app's metrics without an HTTP request. ## When to Embed { #when-to-use } Embed the agent in an app you build and deploy yourself when: - **There's nothing more to deploy.** The agent ships inside the app, so no sidecar, second process, or agent config runs beside each replica. The Ktor plugin and the Spring Boot starter start and stop it with the app. - **The app can't open a metrics port, or shouldn't.** The agent reads the app's metrics registry in-process, so the app needs no `/metrics` endpoint, port, or credentials for a scraper. A worker with no HTTP server is scraped as a web app is. - **The app keeps its secrets.** It can build the agent's settings in code, so no file on disk holds the token or the proxy's certificate. Run a [standalone agent](https://prometheus-proxy.com/getting-started/index.md#start-the-agent) beside the app instead when: - **One agent should scrape several services,** such as every service on a host. Embedding puts an agent in each app, and in each of its replicas. - **The app isn't on the JVM, or isn't yours to rebuild.** - **The agent should upgrade apart from the app.** An embedded agent changes only when the app is released. Its libraries, such as gRPC, Netty, and Ktor, share the app's classpath, so a Ktor or Spring Boot app lines their versions up with the agent's. ## Ways to Run It Each of these runs the same agent from the same settings, the tree a config file holds under `agent` (see [Agent Configuration](https://prometheus-proxy.com/configuration/agent/index.md)): | Your application | Start the agent with | Its settings come from | |:----------------------------------------|:--------------------------------------------------------------------------------------------|:--------------------------------------------------------------------------------------------------------| | A Spring Boot app | The [Spring Boot Starter](https://prometheus-proxy.com/spring-boot-starter/index.md), from a dependency | The `prometheus-proxy.agent.*` properties, and a customizer bean | | A Ktor app | The [Ktor Plugin](https://prometheus-proxy.com/ktor-plugin/index.md), `install(PrometheusProxyAgent)` | `prometheus-proxy.agent` in `application.conf` or its YAML, and the install block | | Any JVM program, its settings in code | [`embeddedAgent { }`](#configuring-in-code), or `EmbeddedAgentConfig.builder()` from Java | The builder's methods, [`fromEnvironment()`](#settings-from-the-environment), and `setting()` | | Any JVM program, its settings in a file | [`Agent.startAsyncAgent(file, false)`](https://prometheus-proxy.com/embedded-api/index.md#agentstartasyncagent) | A HOCON config file or URL, as the standalone agent reads one | | Any JVM program, a `Config` it builds | [`Agent.startAsyncAgent(config)`](#a-config-of-your-own) | A Typesafe `Config`, rooted at `agent` | The starter and the plugin start the agent with the app, and stop it as the app stops. With the others, the app stops it itself (see [`EmbeddedAgentInfo`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo)). The starter and the plugin pass their settings to the builder, and [Every Setting, Every Way](#every-setting-every-way) gives each setting's name in each of them. ## You Need a Proxy The agent connects out to a proxy, which Prometheus scrapes, so start one first. To try it on your machine, run the Quick Start's [steps 1 and 2](https://prometheus-proxy.com/getting-started/index.md#installation), then come back here; [JVM Embed](https://prometheus-proxy.com/embed/index.md#you-need-a-proxy) gives the other ways. The builder's `proxy(...)` tells the agent where the proxy is, or `fromEnvironment()` reads it from `PROMETHEUS_PROXY`, as the examples below do. Without one, `startIfConfigured()` leaves the agent off. ## Adding the Dependency === "Gradle (Kotlin DSL)" ```kotlin // build.gradle.kts repositories { mavenCentral() } dependencies { implementation("com.pambrose:prometheus-proxy:4.9.0") } ``` === "Maven" ```xml com.pambrose prometheus-proxy 4.9.0 ``` The agent runs on Java 17 or later, and an app written in Kotlin compiles with Kotlin 2.4 or later. ## Configuring in Code [`EmbeddedAgentConfig`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentconfig) has a typed method for each setting. Build it with `embeddedAgent { }` from Kotlin, or `EmbeddedAgentConfig.builder()` from Java, and start it. This worker has no HTTP server: the agent reads its metrics registry in-process, on each scrape, and serves it at the proxy's `/worker_metrics`: === "Kotlin" ```kotlin import io.prometheus.agent.embeddedAgent import io.prometheus.metrics.model.registry.PrometheusRegistry // A worker with no HTTP server of its own: the agent reads its metrics from // the registry, in-process, for each scrape, and serves its own beside them. // Without PROMETHEUS_PROXY, as on a developer's machine, the worker runs // without it. fun runWorker( version: String, work: () -> Unit, ) { embeddedAgent { name = "worker-$version" fromEnvironment() // Where the worker's metrics are: Micrometer's PrometheusMeterRegistry // gives its own as prometheusRegistry source( path = "worker_metrics", registry = PrometheusRegistry.defaultRegistry, ) // The agent's own, for the Agents dashboard agentMetricsAt(path = "worker_agent_metrics") }.startIfConfigured(logBanner = false).use { work() } } ``` === "Java" ```java import io.prometheus.agent.EmbeddedAgentConfig; import io.prometheus.agent.EmbeddedAgentInfo; import io.prometheus.metrics.model.registry.PrometheusRegistry; public class EmbeddedAgentSourceJavaExample { // A worker with no HTTP server of its own: the agent reads its metrics // from the registry, in-process, for each scrape, and serves its own // beside them. Without PROMETHEUS_PROXY, as on a developer's machine, the // worker runs without it. public static void runWorker(String version, Runnable work) { EmbeddedAgentConfig config = EmbeddedAgentConfig.builder() .name("worker-" + version) .fromEnvironment() // Where the worker's metrics are: Micrometer's // PrometheusMeterRegistry gives its own with getPrometheusRegistry() .source("worker_metrics", PrometheusRegistry.defaultRegistry) // The agent's own, for the Agents dashboard .agentMetricsAt("worker_agent_metrics") .build(); // Null when the agent stays off, which try-with-resources takes: the // worker runs either way try (EmbeddedAgentInfo agent = config.startIfConfigured(false)) { work.run(); } } } ``` - **[`fromEnvironment()`](#settings-from-the-environment) reads the proxy** from `PROMETHEUS_PROXY`, and a token and the proxy's certificate where they're set. - **[`source(path, registry)`](#metrics-served-in-process) serves the registry,** so the app needs no metrics endpoint, port, or credentials for the agent. - **[`agentMetricsAt(path)`](#the-agents-own-metrics) serves the agent's own metrics** at a separate path. - **[`startIfConfigured()`](#starting-where-theres-a-proxy) starts the agent only where there's a proxy,** and keeps the app running if the agent can't start. `use` stops the agent once the work is done. - **The settings fall back to the built-in defaults,** as a config file's do. A setting the agent can't use throws `ConfigLoadException` from `start()`, and `startIfConfigured()` logs it and returns `null`. - **The agent's variables for single settings still take precedence,** such as `AGENT_TOKEN` or `PROXY_HOSTNAME`, as they do over a config file. Give your application's settings other names, as the `PROMETHEUS_` ones `fromEnvironment()` reads are, unless you mean the agent to read them. `AGENT_CONFIG` isn't read. [Every Setting, Every Way](#every-setting-every-way) lists each setting's variable. ??? note "Which release added these" The builder, `embeddedAgent { }` and `EmbeddedAgentConfig.builder()`, came in 4.6.0; `fromEnvironment()`, `startIfConfigured()`, `source()`, and `agentMetricsAt()` in 4.7.0; and `stopTimeout` in 4.8.0. [Upgrading an Embedded Agent](https://prometheus-proxy.com/embedded-upgrading/index.md) lists what each release changed. ### See the First Scrape Start the app with `PROMETHEUS_PROXY=localhost:50051` in its environment, for a proxy on the same machine. The agent logs, through the app's [logging](https://prometheus-proxy.com/embedded-debugging/index.md#logging), when it has connected and registered each path: ``` { .text .pp-output .pp-output--ok title="The app's log" } Connected to proxy at localhost:50051 using plaintext Registered in-process as /worker_metrics with labels {} (static) Registered in-process as /worker_agent_metrics with labels {} (static) ``` Without `PROMETHEUS_PROXY`, it logs `No proxy is set, so the Prometheus agent stays off` instead, and the worker runs without the agent. Scrape the path through the proxy, as Prometheus will: ```bash curl -i http://localhost:8080/worker_metrics ``` HTTP/1.1 200 OK, followed by the metrics in the worker's registry, means every hop works: the proxy answers scrapes, and the agent is connected and reads the registry. 404 Not Found means no agent has registered the path. Check the app's log for the `Registered` line; [Debugging an Embedded Agent](https://prometheus-proxy.com/embedded-debugging/index.md) shows where else to look. Then give Prometheus a job for the path, with the proxy's host in place of `localhost` where Prometheus runs elsewhere, and have it read the job: ```yaml scrape_configs: - job_name: 'worker' metrics_path: '/worker_metrics' static_configs: - targets: ['localhost:8080'] ``` !!! success "You're done when Prometheus shows `worker` up" After Prometheus's next scrape, its target page (Status → Target health) shows `worker` as up: Prometheus is scraping the worker's registry, in-process, through the proxy. The agent's own metrics, at `/worker_agent_metrics`, take a separate job (see [Agent's Metrics](#the-agents-own-metrics)). ### Metrics Served In-Process Since 4.7.0, an app with a metrics registry can hand it to the agent instead of serving it at a URL, as the worker above does. `source(path, registry)` takes the Prometheus Java client's `PrometheusRegistry`, which Micrometer's `PrometheusMeterRegistry` gives with `getPrometheusRegistry()`. The agent reads it on each scrape, in-process. The app then needs no metrics endpoint, port, or credentials for the agent, and the agent opens no connection to it. A program with no HTTP server at all, such as a worker that consumes a queue, is scraped as a web app is, as the [Plain Kotlin Demo](https://prometheus-proxy.com/plain-kotlin-demo/index.md)'s ovens are. - **The agent writes the format Prometheus asks for:** the Prometheus text format or OpenMetrics, as Prometheus's `Accept` header allows, without the protobuf it can't carry, and only the metric families Prometheus names with `name[]` parameters, if it names any. It brings the Prometheus client's text formats itself, so the app declares nothing more. - **It's read as a target's body is,** on a thread it can block: up to `agent.http.maxContentLengthMBytes`, past which the scrape is refused, and through the path's [metric filter](https://prometheus-proxy.com/configuration/agent/index.md#metric-filtering). - **The agent's own metrics aren't among the app's.** With its metrics on, the agent keeps them in the default registry, `PrometheusRegistry.defaultRegistry`, which a plain program's metrics are often in too; a source of it leaves them out, so each series is served once. [`agentMetricsAt`](#the-agents-own-metrics) serves them at a separate path. - **A source's trouble stays in its scrape.** At the scrape timeout, the agent answers without waiting for it, and whatever reading the registry throws, short of a `VirtualMachineError`, fails the scrape, as a target that can't be reached does, and the agent goes on. - **The path's target shows as `in-process`** on both dashboards and in the agent's log, where a scraped path shows its URL, and Scrape now on the agent's dashboard reads the registry. - **The path is checked as a `pathConfigs` entry is:** one that another path also names, or that has a character the proxy refuses (whitespace, a control character, `?`, or `#`), fails `start()`. A source is code, so `toConfig()` leaves it out: start the agent with the builder's `start()` or `startIfConfigured()`. For metrics in another form, `source(path, source)` takes a `MetricsSource`, which the agent asks for the app's metrics on each scrape. It writes them to the stream it's given, in a format the scrape's `Accept` header allows, and returns the content type it wrote; an empty one means the text format. Calls can overlap, as scrapes do, so it must be safe to call from several threads. At the scrape timeout, the agent interrupts the call; one that ignores the interrupt, such as one blocked on a socket read, keeps its thread, and the source isn't called again until every such call has returned. The agent's `agent_stuck_sources` gauge counts its sources with such a call ([Agent Metrics](https://prometheus-proxy.com/monitoring/index.md#agent-metrics)). Whatever it throws, an `Error` included, fails only its scrape; only a `VirtualMachineError`, such as `OutOfMemoryError`, isn't kept to it. `MetricsSource.of(registry)` is the source `source(path, registry)` gives a registry. ### Scraping the App's Endpoint { #scraping-the-apps-own-endpoint } An app whose metrics the agent can't read in-process can have it scrape the app's `/metrics` over HTTP instead, as a standalone agent does. Settings the app holds itself, such as a token, the proxy's certificate, or the credentials for that endpoint, are built in code, so no config file holds them on disk: === "Kotlin" ```kotlin import io.prometheus.agent.EmbeddedAgentInfo import io.prometheus.agent.embeddedAgent import kotlin.time.Duration.Companion.seconds // Starts the agent from the app's own settings, in memory, so no config file holds the token or the password. Returns // null when the agent is off, without PROMETHEUS_PROXY, or can't start, which it logs: the app's metrics aren't worth // an outage. fun startPrometheusAgent( appVersion: String, appPort: Int, ): EmbeddedAgentInfo? = embeddedAgent { // The version tells the old and new revisions apart during a deploy name = "my-app-$appVersion" // The proxy, its token, and its certificate: PROMETHEUS_PROXY, PROMETHEUS_AGENT_TOKEN, and PROMETHEUS_PROXY_CERT fromEnvironment() // The app's own /metrics, on 127.0.0.1; the agent sends the credentials as Basic Auth scrapeSelf( path = "my_app_metrics", port = appPort, username = env("METRICS_USER"), password = env("METRICS_PASSWORD"), ) // How long the agent's stop may hold up the app's shutdown: inside the platform's window after SIGTERM, such as // Cloud Run's 10 seconds stopTimeout = 8.seconds }.startIfConfigured(logBanner = false) private fun env(name: String) = System.getenv(name).orEmpty().trim() ``` === "Java" ```java import io.prometheus.agent.EmbeddedAgentConfig; import io.prometheus.agent.EmbeddedAgentInfo; import java.time.Duration; public class EmbeddedAgentConfigJavaExample { // Starts the agent from the app's own settings, in memory, so no config file holds the token or the password. // Returns null when the agent is off, without PROMETHEUS_PROXY, or can't start, which it logs: the app's metrics // aren't worth an outage. public static EmbeddedAgentInfo startPrometheusAgent(String appVersion, int appPort) { return EmbeddedAgentConfig.builder() // The version tells the old and new revisions apart during a deploy .name("my-app-" + appVersion) // The proxy, its token, and its certificate: PROMETHEUS_PROXY, PROMETHEUS_AGENT_TOKEN, and PROMETHEUS_PROXY_CERT .fromEnvironment() // The app's own /metrics, on 127.0.0.1; the agent sends the credentials as Basic Auth .scrapeSelf("my_app_metrics", appPort, env("METRICS_USER"), env("METRICS_PASSWORD")) // How long the agent's stop may hold up the app's shutdown: inside the platform's window after SIGTERM, such as // Cloud Run's 10 seconds .stopTimeout(Duration.ofSeconds(8)) .build() .startIfConfigured(false); } private static String env(String name) { String value = System.getenv(name); return value == null ? "" : value.trim(); } } ``` - **The certificate is PEM text,** or its base64 ([`agent.tls.trustCertCollectionPem`](https://prometheus-proxy.com/security/tls/index.md#certificates-as-environment-variables)). - **`scrapeSelf` points the agent at the app's metrics** on `127.0.0.1`. It percent-encodes a username and password into the scrape URL, whatever their characters; the agent sends them as Basic Auth and leaves them out of its logs. - **`stopTimeout` caps how long the agent's stop holds up the app's shutdown.** Set it inside the window the platform gives the app after `SIGTERM`. Once it's up, `shutdown()` returns, and the agent goes on stopping on its own ([`EmbeddedAgentInfo`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo)). The agent's `Registered` line then names the app's URL, `http://127.0.0.1:/metrics`, with any credentials shown as `***`, where the worker's names `in-process`. The first scrape goes as [above](#see-the-first-scrape), at `/my_app_metrics`. ### Agent's Metrics { #the-agents-own-metrics } The [Agents dashboard](https://prometheus-proxy.com/grafana/index.md#dashboards) the project ships reads the agent's own metrics, `agent_connected`, its scrapes, their latency, and its backlog among them. An embedded agent's metrics port would be no more reachable from outside than the app's. So since 4.7.0, `agentMetricsAt(path)` has the agent serve them through the proxy, at a separate path. They're read in-process, as the app's registry is, with no port opened for them. The example above serves them at `/worker_agent_metrics`. `agentMetricsAt(path, labels)` sets `agent.metrics.proxyPath` and `agent.metrics.proxyPathLabels`, the settings a standalone agent uses to serve its metrics through the proxy. So `toConfig()` holds them, and a config file, a `Config`, the starter's and the plugin's `metrics-proxy-path`, or `METRICS_PROXY_PATH` in the app's environment sets the same: - **They're the `agent_*` series, this agent's alone:** another agent in the same JVM serves its own, and the JVM's metrics stay with the app's path, which the dashboard doesn't read them from. A standalone agent's path serves its JVM's metrics too, since its JVM is its own, and so does an `Agent` an app constructs and starts itself: only one started with `startAsyncAgent()` or this builder, as the starter and the plugin start theirs, counts as embedded. - **They're kept from the start,** whether or not the agent's metrics port is on (`agentMetrics(port)`, `METRICS_ENABLED`), and a source of the default registry leaves them out. The [agent's dashboard](https://prometheus-proxy.com/agent-dashboard/index.md) shows them as on in its Settings view, with their path, and their port when it's on too. - **The path is checked as a `pathConfigs` entry is:** one another path also names, or that has a character the proxy refuses, fails `start()`, and the error names `agent.metrics.proxyPath`. - **Give each of the app's replicas a separate path,** as the [Plain Kotlin Demo](https://prometheus-proxy.com/plain-kotlin-demo/index.md) names its replicas' after their host names: replicas sharing one would have the proxy serve only one of them there. - **Give the path a separate Prometheus job,** since the dashboard tells agents apart by `job`: ```yaml scrape_configs: - job_name: worker-agent metrics_path: /worker_agent_metrics static_configs: - targets: [ 'proxy-host:8080' ] ``` The [Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md) serves its coffee shop's agent's metrics this way, and its Grafana links to the dashboard. The metrics port, `agentMetrics(port)`, is for a scraper on the app's network, such as a Prometheus inside the cluster, which can read the agent while it can't reach the proxy, when nothing reaches its path. The port serves everything in the JVM's default registry, the app's metrics too when they're kept there, and the JVM metric groups the agent's `agent.metrics` settings turn on. Without such a scraper, the path is all the agent needs (see [Port or Proxy Path](https://prometheus-proxy.com/monitoring/index.md#port-or-proxy-path)). ### Settings from the Environment Since 4.7.0, `fromEnvironment()` reads the proxy, and how to reach it, from the app's environment. Its variables have names apart from the agent's own. The [Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md), the [Spring Boot Demo](https://prometheus-proxy.com/spring-boot-demo/index.md), and [Cloud Platforms](https://prometheus-proxy.com/cloud-platforms/index.md) use them: | Variable | Sets | |:-----------------------------|:----------------------------------------------------------------------------------------------------------------------------------| | `PROMETHEUS_PROXY` | `proxy`: the proxy's agent port, as `host:port`, or several, separated by commas | | `PROMETHEUS_AGENT_TOKEN` | `token`: the token the agent presents to the proxy | | `PROMETHEUS_PROXY_CERT` | `trustCertificatePem`: the certificate the agent trusts the proxy's by, as PEM or its base64, which turns TLS on | | `PROMETHEUS_PROXY_AUTHORITY` | The certificate's authority, the name the proxy's certificate was issued to; `prometheus-proxy` when unset. Read only with the certificate | - **The authority defaults to `prometheus-proxy`,** the name the certificate [Securing the Link](https://prometheus-proxy.com/cloud-platforms/index.md#securing-the-link) makes is issued to. To check the proxy's certificate against the host the agent connects to, as for a certificate from a public CA, set `PROMETHEUS_PROXY_AUTHORITY` to that host. - **A variable that's unset, or blank, leaves its setting alone,** so a builder method called after `fromEnvironment()` takes precedence, and one called before it holds where the variable isn't set. A `setting()` of the same key takes precedence whatever its order, as it does over any builder method, and the variable's value then isn't checked. - **Only `fromEnvironment()` reads these:** the agent doesn't, so an app that never calls it can use the names for anything. - **A value the agent refuses names its variable.** A `PROMETHEUS_PROXY` endpoint the agent can't parse, or a `PROMETHEUS_PROXY_CERT` it can't read as a certificate, fails `start()`, or has `startIfConfigured()` log, with the variable, the setting, and the agent's reason: `Invalid configuration: PROMETHEUS_PROXY, read by fromEnvironment() for agent.proxy.endpoints: Invalid port in 'proxy:abc': 'abc' is not a valid integer`. An endpoint it can't parse is quoted, as here, but never a certificate. The agent takes any token or authority as it starts: a token the proxy refuses is logged once the agent connects ([Troubleshooting](https://prometheus-proxy.com/troubleshooting/index.md#unauthenticated-missing-or-invalid-agent-token)), and a wrong authority fails the TLS handshake. ### Starting Where There's a Proxy `start()` throws when the agent can't start, which suits an app that can't run without it. Since 4.7.0, `startIfConfigured()` suits one that can, as most can, since their metrics aren't worth an outage: - **Without a proxy,** as on a developer's machine, it logs one INFO line, `No proxy is set, so the Prometheus agent stays off`, and returns `null`. A proxy comes from the builder's `proxy`, a `setting()` of the proxy's endpoints or host name, or the agent's `PROXY_HOSTNAME`. `namesProxy()` tells whether the settings name one, for an app that decides for itself, as the [Ktor Plugin](https://prometheus-proxy.com/ktor-plugin/index.md) and the [Spring Boot Starter](https://prometheus-proxy.com/spring-boot-starter/index.md) do. - **A start that fails returns `null`,** so the app runs on. That covers a setting the agent rejects, and anything else, such as its admin port being in use or its start taking over 30 seconds. It's logged at ERROR, as `The Prometheus agent could not start, so it stays off:` and why, which holds no token, password, or PEM. - **To report a failed start elsewhere,** such as to a chat channel, add a handler with the builder's `onFailure`, since 4.8.0. It's given why, as the log line has it, and what was thrown. Each handler added runs in turn, and one that throws is logged without failing the start. So a [Ktor](https://prometheus-proxy.com/ktor-plugin/index.md) `agent { }` block or a [Spring Boot](https://prometheus-proxy.com/spring-boot-starter/index.md) customizer can add one beside the app's own. `startIfConfigured(onFailure)` still takes one too, which runs after them. `start()` tells none of them: it throws, for its caller to handle. - **A host that makes the settings from its configuration** before the app's code adds its handlers, as those two do, reports a value there that a builder method rejects with the builder's `reportFailure(cause)`. That logs it as a failed start is logged, and tells the handlers. - **The handle is `AutoCloseable`,** and Kotlin's `use` and Java's try-with-resources both take a `null` one. So a program that runs while its agent does reads as `startIfConfigured().use { worker.run() }`. The worker runs whether or not the agent started, and the agent stops after it. Write `.use`, not `?.use`, which skips the block for `null`. A program that runs until it's stopped needs a shutdown hook too (see [`EmbeddedAgentInfo`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo)). === "Kotlin" ```kotlin val agent = embeddedAgent { // The agent's other settings fromEnvironment() onFailure { reason, _ -> alerts.send("No metrics from this app: $reason") } }.startIfConfigured(logBanner = false) ``` === "Java" ```java EmbeddedAgentInfo agent = EmbeddedAgentConfig.builder() // The agent's other settings .fromEnvironment() .onFailure((reason, e) -> alerts.send("No metrics from this app: " + reason)) .build() .startIfConfigured(false); ``` A wrong token isn't a failure to start: the agent starts, and the proxy refuses it once it connects. The agent logs that at ERROR, naming the setting, and keeps retrying (see [Troubleshooting](https://prometheus-proxy.com/troubleshooting/index.md#unauthenticated-missing-or-invalid-agent-token)). ### A `Config` of Your Own For a setting the builder has no method for, `setting(key, value)` sets it by its key, relative to `agent`, such as `setting("scrapeTimeoutSecs", 5)`. A key the agent doesn't know has no effect, and the agent warns about it as it starts, naming the nearest setting. Or build the whole tree as a Typesafe `Config` rooted at `agent`, the tree a config file holds, and start it with `Agent.startAsyncAgent(config)`. `ConfigFactory.parseString`, `ConfigFactory.parseMap`, and `ConfigValueFactory.fromMap` build one, and a builder's `toConfig()` gives the one it holds. It's resolved, as a config file is, so a `${?ENV_VAR}` substitution in it works. [Cloud Platforms](https://prometheus-proxy.com/cloud-platforms/index.md) builds on this to run an embedded agent in an app on ECS on Fargate, Cloud Run, Azure Container Apps, or another platform, with the proxy on AWS, GCP, Azure, DigitalOcean, or Railway. The [Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md) runs an embedded agent on one machine, in a Ktor app, with the [Ktor Plugin](https://prometheus-proxy.com/ktor-plugin/index.md). The [Plain Kotlin Demo](https://prometheus-proxy.com/plain-kotlin-demo/index.md) runs one in each of a plain Kotlin program's replicas, with no framework or HTTP server, scaled out and in. ## Configuring with a File { #usage } An app that keeps the agent's settings in a file, as the standalone agent does, starts it with [`Agent.startAsyncAgent()`](https://prometheus-proxy.com/embedded-api/index.md#agentstartasyncagent), which reads the file or a URL: === "Kotlin" ```kotlin import io.prometheus.Agent fun main() { // Start the agent in the background. It stops when the block ends, however it ends. Agent.startAsyncAgent( configFilename = "agent-config.conf", exitOnMissingConfig = false, ).use { agentInfo -> println("Agent started: ${agentInfo.agentName}") // Your application code runs here... // The agent runs in background coroutines } } ``` === "Java" ```java import io.prometheus.Agent; import io.prometheus.agent.EmbeddedAgentInfo; public class EmbeddedAgentJavaExample { public static void main(String[] args) { // Start the agent in the background. false makes a config error throw instead of exiting the JVM; a third // argument, false, would leave out the startup banner. The agent stops when the block ends, however it ends. try (EmbeddedAgentInfo agentInfo = Agent.startAsyncAgent("agent-config.conf", false)) { System.out.println("Agent started: " + agentInfo.getAgentName()); // Your application code runs here... // The agent runs in background threads } } } ``` The file holds the same HOCON settings as the standalone agent's (see [Agent Configuration](https://prometheus-proxy.com/configuration/agent/index.md)): ```hocon // Minimal config for an embedded agent: agent { proxy.hostname = "proxy-host.example.com" pathConfigs: [ { name: "My App metrics" path: my_app_metrics url: "http://localhost:9100/metrics" } ] } ``` A relative file path is read from the app's working directory, so use an absolute path where that differs. ## Every Setting, Every Way A setting has a name in each way of giving it. The builder's methods, the starter's properties, and the plugin's keys all set the agent's config keys, the ones a config file holds. The agent reads each key's environment variable itself, embedded or not: | Setting | Builder | Config key | Starter property, plugin key | Environment variable | |:--------------------------------|:----------------------------------------------------|:---------------------------------------------------------------------------|:---------------------------------------------------|:-------------------------------------------------------| | The proxy | `proxy(endpoints…)` | `agent.proxy.endpoints` | `proxy` | `PROXY_HOSTNAME` | | The token | `token(token)` | `agent.agentToken` | `token` | `AGENT_TOKEN` | | The proxy's certificate | `trustCertificatePem(pem, authority)` | `agent.tls.trustCertCollectionPem`, `agent.tls.overrideAuthority` | `trust-certificate`, `authority` | `TRUST_CERT_COLLECTION_PEM`, `OVERRIDE_AUTHORITY` | | The agent's certificate and key | `clientCertificatePem(certChainPem, privateKeyPem)` | `agent.tls.certChainPem`, `agent.tls.privateKeyPem` | `client-certificate`, `client-key` | `CERT_CHAIN_PEM`, `PRIVATE_KEY_PEM` | | The agent's name | `name(name)` | `agent.name` | `name` | `AGENT_NAME` | | Consolidated mode | `consolidated(consolidated)` | `agent.consolidated` | `consolidated` | `CONSOLIDATED` | | Its metrics, on a port | `agentMetrics(port)` | `agent.metrics.enabled`, `agent.metrics.port` | `metrics-port` | `METRICS_ENABLED`, `METRICS_PORT` | | Its metrics, through the proxy | `agentMetricsAt(path, labels)` | `agent.metrics.proxyPath`, `agent.metrics.proxyPathLabels` | `metrics-proxy-path`, `metrics-proxy-path-labels` | `METRICS_PROXY_PATH` | | Its direct dashboard | `dashboard(port, host)` | `agent.dashboard.enabled`, `agent.dashboard.port`, `agent.dashboard.host` | `dashboard.port`, `dashboard.host` | `DASHBOARD_ENABLED`, `DASHBOARD_PORT`, `DASHBOARD_HOST` | | Its direct dashboard's login | `dashboardLogin(password, username)` | `agent.dashboard.password`, `agent.dashboard.username` | `dashboard.password`, `dashboard.username` | `DASHBOARD_PASSWORD`, `DASHBOARD_USERNAME` | | Its direct dashboard's framing | `setting("dashboard.framingEnabled", false)` | `agent.dashboard.framingEnabled` | `settings.dashboard.framingEnabled` | | | Its relayed dashboard | `setting("dashboard.showOnProxy", false)` | `agent.dashboard.showOnProxy` | `settings.dashboard.showOnProxy` | | | A target it scrapes | `path(…)`, `scrapeSelf(…)` | `agent.pathConfigs` | `paths` | | | The app's registry | `source(path, registry)` | none: it's code | `path` and `labels`, with the app's registry | | | Its stop's timeout | `stopTimeout(timeout)` | none: it's the handle's | `stop-timeout` | | | Anything else | `setting(key, value)` | the key | `settings.` | the key's, if it has one | The starter serves the app's `PrometheusRegistry` bean at `path` unless its `source` is `none`. The plugin serves the registry its install block gives. `fromEnvironment()`'s `PROMETHEUS_` variables are the app's, which only it reads ([Settings From the Environment](#settings-from-the-environment)). The variables above are the agent's own, which it reads whether or not the app asks, so keep their names out of the app's environment unless you mean the agent to use them. Where one setting is given more than one way, the first of these that gives it wins: 1. **The agent's environment variable,** such as `AGENT_TOKEN`, read as the agent starts. 2. **`setting(key, value)`,** and the starter's and the plugin's `settings.`, which call it. 3. **A builder method,** its last call; the starter's customizers and the plugin's install block run after the properties or the file, so their calls replace what those set. 4. **The built-in default** (see [Agent Configuration](https://prometheus-proxy.com/configuration/agent/index.md)). A config file or a `Config` takes the place of the second and third: its keys, then the defaults. ### Settings without a Builder Method `setting(key, value)` sets any other setting by its key under `agent`, as the starter's and the plugin's `settings.` do. These are the ones an embedded agent most often needs: | Config key | Default | What it sets | |:---------------------------------------|:--------|:-----------------------------------------------------------------------------------------------------------------------| | `agent.scrapeTimeoutSecs` | 15 | How long the agent waits for a target's answer, in seconds | | `agent.scrapeMaxRetries` | 0 | How many times it retries a failed scrape | | `agent.http.maxConcurrentClients` | 1 | How many scrapes it runs at once; raise it when it scrapes several slow targets | | `agent.http.clientTimeoutSecs` | 90 | Its HTTP client's timeout, in seconds | | `agent.http.maxContentLengthMBytes` | 10 | The largest scrape it takes, in megabytes | | `agent.http.trustStorePath` | "" | A trust store for HTTPS targets signed by a private CA, with `agent.http.trustStorePassword` | | `agent.transportFilterDisabled` | false | Set it, as on the proxy, when [nginx fronts the proxy](https://prometheus-proxy.com/advanced/index.md#nginx-reverse-proxy) | | `agent.admin.enabled` | false | The admin endpoints, on `agent.admin.port`, and `/debug` with `agent.admin.debugEnabled` ([Admin and Debug Endpoints](https://prometheus-proxy.com/embedded-debugging/index.md#admin-and-debug-endpoints)) | | `agent.logLevel` | "" | The level of the agent's `io.prometheus` loggers, and no others; unset, they follow your application's logging ([Logging](https://prometheus-proxy.com/embedded-debugging/index.md#logging)) | | `agent.metrics.standardExportsEnabled` | false | The process metrics, one of the [JVM metric groups](https://prometheus-proxy.com/monitoring/index.md#jvm-metrics), which the agent's metrics port serves | An embedded agent's JVM metrics are usually its app's, which its registry, such as Micrometer's, keeps and serves: the agent's JVM metric groups add only to what its metrics port serves, and do nothing with the port off. A list or an object, such as `filters` or `discovery`, is clearer in a config file or a `Config` (see [A `Config` of Your Own](#a-config-of-your-own)); [Agent Configuration](https://prometheus-proxy.com/configuration/agent/index.md) describes every setting. ## In Ktor The [Ktor Plugin](https://prometheus-proxy.com/ktor-plugin/index.md) runs the agent in a Ktor app. `install(PrometheusProxyAgent)` starts it with the app, stops it with the server, and serves the app's registry in-process. ## In Spring Boot The [Spring Boot Starter](https://prometheus-proxy.com/spring-boot-starter/index.md) runs the agent in a Spring Boot app from a dependency and a few properties, and reports its connection in Actuator's health. To wire the agent into the app yourself, see [Without the Starter](https://prometheus-proxy.com/spring-boot-starter/index.md#without-the-starter). ## API Reference [Embedded Agent API](https://prometheus-proxy.com/embedded-api/index.md) lists the methods and types: [`Agent.startAsyncAgent()`](https://prometheus-proxy.com/embedded-api/index.md#agentstartasyncagent), [`EmbeddedAgentConfig`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentconfig), [`EmbeddedAgentInfo`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo), and [`Agent.startSyncAgent()`](https://prometheus-proxy.com/embedded-api/index.md#agentstartsyncagent). ## How It Works When you call `startAsyncAgent()`: 1. The agent reads the configuration file, or the config you passed 2. Starts its admin, metrics, and dashboard servers, if enabled, and waits for them to come up 3. Returns with agent metadata, without waiting for a proxy connection 4. Connects to the proxy and registers paths in the background 5. Keeps running in the background, processing scrape requests Your application code runs normally while the agent handles metrics scraping in the background. ??? info "The agent's metrics in your application's registry" With its metrics on, on their port (`agentMetrics(port)`, `agent.metrics.enabled`) or at a proxy path (`agentMetricsAt(path)`, `agent.metrics.proxyPath`), the embedded agent's metrics register in the Prometheus Java client 1.x default registry (`io.prometheus.metrics.model.registry.PrometheusRegistry.defaultRegistry`). A host that serves its metrics from that registry over HTTP exposes the agent's too, though the agent's `source(path, registry)` of it leaves them out; a host still on the 0.x client (`io.prometheus:simpleclient`) does not see them. Every agent in the JVM, two at once or one started again after `shutdown()`, shares one set of agent metrics, and each series carries the agent's `launch_id`. An agent's series go when it shuts down. A host metric with one of the agent metrics' names makes `startAsyncAgent()` throw. ## Logging Your application configures the agent's logging, which goes through SLF4J. [Logging](https://prometheus-proxy.com/embedded-debugging/index.md#logging) says how it goes with Logback, with another provider, and with none. ## Debugging [Debugging an Embedded Agent](https://prometheus-proxy.com/embedded-debugging/index.md) shows how to see what the agent is doing: its admin and debug endpoints, its dashboard, its log, and the proxy's view of it. ## Upgrading What each release since 4.0 changed for code that embeds the agent, and what to do about it, is on [Upgrading an Embedded Agent](https://prometheus-proxy.com/embedded-upgrading/index.md). --- Source: https://prometheus-proxy.com/ktor-plugin/ # Ktor Plugin A Ktor app can run the [embedded agent](https://prometheus-proxy.com/embedded-agent/index.md) by installing a plugin, `com.pambrose:prometheus-proxy-ktor`. The plugin starts the agent with the app, stops it with the app, and serves the app's metrics registry to Prometheus through the proxy. The agent reads the registry in-process, so the app needs no `/metrics` route, no credentials for one, and no port for the agent to scrape. The [Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md)'s coffee shop runs it, under load, with Grafana. ## You Need a Proxy The agent connects out to a proxy, which Prometheus scrapes, so start one first. To try it on your machine, run the Quick Start's [steps 1 and 2](https://prometheus-proxy.com/getting-started/index.md#installation), then come back here; [JVM Embed](https://prometheus-proxy.com/embed/index.md#you-need-a-proxy) gives the other ways. The `proxy` key in `application.conf`, or `proxy(...)` in the `agent { }` block, tells the agent where the proxy is. The examples below read it from `PROMETHEUS_PROXY`, and leave the agent off without it. ## Adding the Dependency === "Gradle (Kotlin DSL)" ```kotlin // build.gradle.kts: the plugin, and Micrometer for the app's metrics registry dependencies { implementation("com.pambrose:prometheus-proxy-ktor:4.9.0") implementation("io.ktor:ktor-server-metrics-micrometer:$ktorVersion") implementation("io.micrometer:micrometer-registry-prometheus:$micrometerVersion") } ``` === "Maven" ```xml com.pambrose prometheus-proxy-ktor 4.9.0 io.ktor ktor-server-metrics-micrometer-jvm ${ktor.version} io.micrometer micrometer-registry-prometheus ${micrometer.version} ``` The plugin needs Ktor 3, Kotlin 2.4 or later, and Java 17 or later. It's released with the agent, at the agent's version. The agent runs Ktor itself, for its HTTP client and its dashboard, so the app's Ktor must be the agent's version or later. Gradle picks the later of the two on its own. Maven picks the version nearest the app, so in a Maven app, declare the Ktor modules, or import `io.ktor:ktor-bom`, at the agent's version or later. ## Installing Install it with the app's registry and the path Prometheus scrapes it at. Give the agent its proxy, here from the app's environment with [`fromEnvironment()`](https://prometheus-proxy.com/embedded-agent/index.md#settings-from-the-environment): ```kotlin fun Application.module() { // Ktor's HTTP metrics and the JVM's, then the app's own, in one registry val meterRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT) install(MicrometerMetrics) { registry = meterRegistry } install(PrometheusProxyAgent) { // Served in-process, at the proxy's /my_app_metrics registry = meterRegistry.prometheusRegistry path = "my_app_metrics" agent { name = "my-app" // PROMETHEUS_PROXY, PROMETHEUS_AGENT_TOKEN, and PROMETHEUS_PROXY_CERT. Without PROMETHEUS_PROXY, as on a // developer's machine, the agent stays off fromEnvironment() } } routing { agentHealth() } } ``` With that, the app gets: - **An agent that starts and stops with the app.** It starts once every module of the app has loaded. It begins stopping as soon as the server does, before the server drains the requests in flight: the agent disconnects, the proxy drops its paths, and no scrape reaches an app that's going away. The app's shutdown waits for it, up to the agent's `stopTimeout`, 30 seconds by default, without taking that time from the server's grace period. In development mode, a reload stops the old app's agent and starts the new one's. - **Its metrics at the proxy's `/my_app_metrics`,** read from the registry for each scrape. The agent writes the format Prometheus asks for, within its limits and through the path's filter, as [Metrics Served In-Process](https://prometheus-proxy.com/embedded-agent/index.md#metrics-served-in-process) describes. Micrometer's `PrometheusMeterRegistry` gives its registry as `prometheusRegistry`; an app on the Prometheus Java client gives its own, such as `PrometheusRegistry.defaultRegistry`. A registry needs a path, which has no default, since two apps given the same one would take the path from each other. - **An app that runs without an agent that can't start.** Without a proxy, as on a developer's machine or in `testApplication`, the agent logs a line and stays off. The proxy can come from the file, the install block, or the agent's `PROXY_HOSTNAME`. A setting the agent rejects, such as an unreadable certificate, is logged, and the agent stays off without stopping the app. To have the app fail to start instead, also when there's no proxy, set `required = true`. To have the app told why, add an `onFailure` handler in the `agent { }` block ([below](#a-failed-start-and-the-stop)). The `agent { }` block takes the agent's [`EmbeddedAgentConfig.Builder`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentconfig), with a typed method for each setting, such as a certificate the app reads from a secret store. Its `agentMetricsAt(path)` serves the [agent's own metrics](https://prometheus-proxy.com/embedded-agent/index.md#the-agents-own-metrics) through the proxy too, with no port, as the file's `metrics-proxy-path` does. As with any embedded agent, the agent's environment variables, such as `AGENT_TOKEN` or `PROXY_HOSTNAME`, take precedence over its settings, and `PROXY_HOSTNAME` alone starts the agent. Give the app's variables other names, as `fromEnvironment()`'s `PROMETHEUS_` ones are. ## See the First Scrape Start the app with `PROMETHEUS_PROXY=localhost:50051` in its environment, for a proxy on the same machine. A Ktor app often listens on 8080, as the proxy's scrape port does, so on one machine, give the app another, such as with `ktor.deployment.port`. Once the app has started, the agent logs, through the app's [logging](https://prometheus-proxy.com/embedded-debugging/index.md#logging), when it has connected and registered the path: ``` { .text .pp-output .pp-output--ok title="The app's log" } Connected to proxy at localhost:50051 using plaintext Registered in-process as /my_app_metrics with labels {} (static) ``` Without a proxy, the plugin logs `No proxy is set (prometheus-proxy.agent.proxy or PROXY_HOSTNAME), so the Prometheus agent stays off` instead. Scrape the path through the proxy, as Prometheus will: ```bash curl -i http://localhost:8080/my_app_metrics ``` ``` { .text .pp-output .pp-output--ok title="curl's output, in part" } HTTP/1.1 200 OK Content-Type: text/plain; version=0.0.4; charset=utf-8 # HELP jvm_threads_live_threads The current number of live threads including both daemon and non-daemon threads # TYPE jvm_threads_live_threads gauge jvm_threads_live_threads 30.0 ``` The body is the app's registry, read in-process: the JVM's metrics, which `MicrometerMetrics` binds, the app's own, and Ktor's HTTP metrics once the app has served a request. 404 Not Found means no agent has registered the path. Check the app's log for the `Registered` line; [Debugging an Embedded Agent](https://prometheus-proxy.com/embedded-debugging/index.md) shows where else to look. Then give Prometheus a job for the path, with the proxy's host in place of `localhost` where Prometheus runs elsewhere, and have it read the job: ```yaml scrape_configs: - job_name: 'my-app' metrics_path: '/my_app_metrics' static_configs: - targets: ['localhost:8080'] ``` !!! success "You're done when Prometheus shows `my-app` up" After Prometheus's next scrape, its target page (Status → Target health) shows `my-app` as up: Prometheus is scraping the app's registry, in-process, through the proxy. ## A Failed Start, and the Stop Since 4.8.0, the `agent { }` block can add a failure handler and set a stop timeout. Both are the builder's settings, so they go in the block, as for any [embedded agent](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentconfig). An agent that can't start stays off while the app runs on, and the plugin logs why. To be told too, add a handler in the block with `onFailure { reason, cause -> }`. It's given the log's reason, which holds no token, password, or PEM, and what was thrown, so the app can send it where someone will see it, such as a chat channel. The handlers are also told of a failure before the agent's start, such as a value in the file the plugin can't read, or an `agent { }` block that throws. The plugin runs every block whatever failed, so each block's handler is added before they're told. Only an `enabled` or `required` the plugin can't read fails the app's start instead, since those decide whether the agent starts. The handlers aren't told of a `required` agent's failure, which fails the app's start, nor of an agent left off on purpose, not `enabled` or without a proxy. A handler that throws is logged, without failing the app's start. `stopTimeout` is how long the app's shutdown waits for the agent's stop: 30 seconds, unless the file's `stop-timeout` or the block sets another. Set it inside the shutdown window the app's platform gives, such as Cloud Run's 10 seconds after `SIGTERM`. Once it's up, the app stops anyway, with a warning, and the agent goes on stopping on its own. An app that stops while its agent is still starting stops the agent as soon as it has started. ```kotlin fun Application.moduleWithFailureAlerts(alert: (String) -> Unit) { val meterRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT) install(MicrometerMetrics) { registry = meterRegistry } // The rest comes from prometheus-proxy.agent in application.conf install(PrometheusProxyAgent) { registry = meterRegistry.prometheusRegistry agent { // Inside the platform's shutdown window, such as Cloud Run's 10 seconds after SIGTERM stopTimeout = 5.seconds // An agent that can't start stays off, and the app runs on without it: this tells someone why onFailure { reason, _ -> alert("The Prometheus agent could not start: $reason") } } } } ``` ## Settings in application.conf An app that reads its settings from a file, through `EngineMain` or `configure()`, can keep the agent's there too. Put them under `prometheus-proxy.agent`, in HOCON or the same keys in YAML: ```hocon prometheus-proxy.agent { // Unset, as on a developer's machine, the agent stays off proxy = ${?PROMETHEUS_PROXY} token = ${?PROMETHEUS_AGENT_TOKEN} name = my-app // The proxy's path the app's registry is served at, and its labels in the proxy's service discovery path = my_app_metrics labels { team = web } } ``` The install block is then left with what a file can't hold, the registry: ```kotlin fun Application.moduleWithFileSettings() { val meterRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT) install(MicrometerMetrics) { registry = meterRegistry } // The rest comes from prometheus-proxy.agent in application.conf install(PrometheusProxyAgent) { registry = meterRegistry.prometheusRegistry } } ``` The install block runs after the file is read, so a setting it makes takes precedence. A `settings.` key is the exception: it takes precedence over the builder's methods, as anything `setting()` sets does, so change one with `setting()` and its key. An app started with `embeddedServer` reads no file, so it has only the block's settings. The keys are the [Spring Boot Starter](https://prometheus-proxy.com/spring-boot-starter/index.md)'s properties. A blank value, such as an unset environment variable gives, counts as unset. A key the plugin doesn't read has no effect, and the plugin warns about it at startup, naming the nearest key below: | Key | Default | What it sets | |----------------------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `proxy` | | The proxy, as `host` or `host:port` (the port defaults to 50051), or several, separated by commas, in the order the agent fails over through them. Unset, the agent stays off, unless the install block, a `settings` key, or `PROXY_HOSTNAME` names one | | `token` | | The token the agent presents to the proxy, which has to match the proxy's | | `trust-certificate` | | The certificate the agent trusts the proxy's by, as PEM text or its base64, which turns [TLS](https://prometheus-proxy.com/security/tls/index.md) on | | `authority` | | The name the proxy's certificate was issued to, when it isn't the host the agent connects to; used with `trust-certificate` | | `client-certificate` | | The agent's certificate chain, as PEM text or its base64, for a proxy that requires mutual TLS | | `client-key` | | The private key of `client-certificate`, as PEM text or its base64 | | `name` | `Unnamed-` and the host | The agent's name, as the proxy's dashboard and logs show it | | `path` | | The proxy's path the registry is served at; required with a registry | | `labels.` | | The labels of the registry's path, in the proxy's [service discovery](https://prometheus-proxy.com/service-discovery/index.md) | | `paths` | | Other targets the agent scrapes over HTTP, a list, each served at its `path` from its `url`, with `username`, `password`, and `labels`; an entry without a `path` or a `url` fails the agent's start | | `consolidated` | `false` | Whether the agent registers its paths in [consolidated mode](https://prometheus-proxy.com/advanced/index.md#consolidated-mode), alongside other agents serving them | | `metrics-port` | | The port of the agent's own metrics, which are off without one, for a scraper on the app's network ([Port or Proxy Path](https://prometheus-proxy.com/monitoring/index.md#port-or-proxy-path)) | | `metrics-proxy-path` | | The proxy's path the [agent's own metrics](https://prometheus-proxy.com/embedded-agent/index.md#the-agents-own-metrics) are served at, read in-process, with no port; off without one. They stay apart from the app's path, whose JVM metrics they'd repeat | | `metrics-proxy-path-labels.` | | The labels of `metrics-proxy-path`, in the proxy's [service discovery](https://prometheus-proxy.com/service-discovery/index.md) | | `dashboard.port`, `.host` | | The agent's direct [dashboard](https://prometheus-proxy.com/agent-dashboard/index.md), off without a port, listening on every interface unless `host` names one, such as `127.0.0.1` | | `dashboard.password` | | Requires a login to the direct dashboard, as `dashboard.username` (`admin` by default) | | `required` | `false` | Whether the app fails to start when the agent can't, or has no proxy | | `stop-timeout` | `30s` | Since 4.8.0, the agent's `stopTimeout`: how long the app's shutdown waits for its stop, more than zero, as a number of seconds or a duration such as `10s` or `PT10S` | | `settings.` | | Any other [agent setting](https://prometheus-proxy.com/configuration/agent/index.md), by its key under `agent`, such as `settings.scrapeTimeoutSecs = 20`. It takes precedence over the keys above | | `enabled` | `true` | Whether to run the agent at all | `enabled`, `required`, `path`, and `labels` are the install block's properties too; the rest are the builder's. A proxy with agent screens on shows the agent's relayed dashboard on its screens page, whether or not `dashboard.port` turns its direct dashboard on. The proxy reaches it through the agent's connection, and shows it to everyone who can sign in to the proxy's dashboard ([Showing It as a Relayed Agent Dashboard](agent-dashboard.md#showing-it-on-the-proxy)); [Direct and Relayed Agent Dashboards](agent-dashboard.md#direct-and-relayed-agent-dashboards) compares the two. To keep the app's agent off every proxy's screens page, set `settings.dashboard.showOnProxy = false` in the file's `prometheus-proxy.agent` section, or call `setting("dashboard.showOnProxy", false)` in an `agent { }` block. ## The Agent's Connection While the agent runs, `application.prometheusProxyAgent` is its [`EmbeddedAgentInfo`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo), which reads its connection to the proxy live. It's null while the agent is off. A route can show it: ```kotlin // The agent's connection, for a dashboard or a person; always 200, since a proxy that's away shouldn't take the app // out of a load balancer or have it restarted fun Route.agentHealth() { get("/health/agent") { val agent = call.application.prometheusProxyAgent val status = when { agent == null -> "off" agent.isConnected -> "connected to ${agent.proxyEndpoint}" else -> "connecting" } call.respondText(status) } } ``` The agent starts before the server listens on its port. The registry doesn't mind, but a scrape of the app's port, from `paths` or the builder's `scrapeSelf`, can fail in that moment. A server that can't listen, on a port another process holds, fails the app's start, and the app still exits. The agent's thread doesn't keep the JVM running, and Ktor's shutdown hook stops the agent as the JVM exits. A `metrics-port` or admin port that's on is the exception: that port's server does keep the JVM running. `metrics-proxy-path` opens no port. ## Without the Plugin [Configuring in Code](https://prometheus-proxy.com/embedded-agent/index.md#configuring-in-code) on the Embedded Agent page starts the agent from any app, in Ktor or not, with its settings built in code. The app stops it by calling `shutdown()`. --- Source: https://prometheus-proxy.com/spring-boot-starter/ # Spring Boot Starter A Spring Boot app can run the [embedded agent](https://prometheus-proxy.com/embedded-agent/index.md) with a dependency and a few properties. The starter, `com.pambrose:prometheus-proxy-spring-boot-starter`, starts the agent with the app, serves the app's metrics to Prometheus through the proxy, and reports the agent's connection in Actuator's health. The agent reads the app's metrics registry in-process. The app needs no `/actuator/prometheus` endpoint, no credentials for one, and no web server at all: a worker that consumes a queue is scraped as a web app is. The [Spring Boot Demo](https://prometheus-proxy.com/spring-boot-demo/index.md) runs it in a roastery app. ## You Need a Proxy The agent connects out to a proxy, which Prometheus scrapes, so start one first. To try it on your machine, run the Quick Start's [steps 1 and 2](https://prometheus-proxy.com/getting-started/index.md#installation), then come back here; [JVM Embed](https://prometheus-proxy.com/embed/index.md#you-need-a-proxy) gives the other ways. The `prometheus-proxy.agent.proxy` property tells the agent where the proxy is. The example below reads it from `PROMETHEUS_PROXY`, and leaves the agent off without it. ## Adding the Dependency === "Gradle (Kotlin DSL)" ```kotlin // build.gradle.kts, with Spring Boot's dependency management // (the io.spring.dependency-management plugin) dependencies { implementation("com.pambrose:prometheus-proxy-spring-boot-starter:4.9.0") implementation("org.springframework.boot:spring-boot-starter-actuator") } ``` === "Maven" ```xml com.pambrose prometheus-proxy-spring-boot-starter 4.9.0 org.springframework.boot spring-boot-starter-actuator ``` The starter runs on Spring Boot 4.0 or later and Java 17 or later, and an app written in Kotlin compiles with Kotlin 2.4 or later. It's released with the agent, at the agent's version. On Spring Boot 4.0 or 4.1, it also needs the two versions below. The starter brings Micrometer's Prometheus registry. With Actuator, or with `spring-boot-starter-micrometer-metrics` in an app without it, Spring Boot puts the app's meters in a `PrometheusRegistry` bean, which the agent serves. Spring Boot's dependency management sets that registry's version, as it does the app's dependencies'. On Spring Boot 4.0 or 4.1, set `kotlin-coroutines.version` to `1.11.0` and `prometheus-client.version` to `1.10.0`. Their dependency management sets kotlinx-coroutines and the Prometheus Java client below the versions the agent runs on. Without the two properties, the agent doesn't start, and the reason it gives names each one: === "Gradle (Kotlin DSL)" ```kotlin // build.gradle.kts, on Spring Boot 4.0 or 4.1, with the // io.spring.dependency-management plugin extra["kotlin-coroutines.version"] = "1.11.0" extra["prometheus-client.version"] = "1.10.0" ``` === "Maven" ```xml 1.11.0 1.10.0 ``` ## Configuring Only the proxy is needed. Read it, and the rest, from the environment, so the agent stays off where it isn't set, as on a developer's machine: ```yaml spring: application: name: roastery prometheus-proxy: agent: # Unset, as on a developer's machine, the agent stays off proxy: ${PROMETHEUS_PROXY:} token: ${PROMETHEUS_AGENT_TOKEN:} # The certificate the proxy's is signed with, and the name the proxy's certificate was issued to: without # PROMETHEUS_PROXY_AUTHORITY, prometheus-proxy, as fromEnvironment() has it, the name Cloud Platforms issues it to trust-certificate: ${PROMETHEUS_PROXY_CERT:} authority: ${PROMETHEUS_PROXY_AUTHORITY:prometheus-proxy} # How long the agent's stop may hold up the app's shutdown: inside the platform's window after SIGTERM, such as # Cloud Run's 10 seconds stop-timeout: 8s ``` With that, the app gets: - **An agent that starts and stops with the app.** It starts once the app is up, in the last lifecycle phase. It stops first on shutdown, before a graceful shutdown drains the web server: the agent disconnects, the proxy drops its paths, and no scrape reaches an app that's going away. The shutdown waits for that up to `stop-timeout`, 30 seconds by default. Spring's phase timeout doesn't cut it short, since the stop runs in the agent bean's `stop()`. - **An app that exits when its work is done.** The agent's thread doesn't keep the JVM running. An app with no web server or other thread to hold it, such as a batch job, exits once `main` returns, and the context's shutdown stops the agent. To keep such an app running, set `spring.main.keep-alive: true`. - **Its metrics at the proxy's `/roastery_metrics`,** the app's name followed by `_metrics`. The agent reads them from the app's registry for each scrape, and writes the format Prometheus asks for, within its limits and through the path's filter, as [Metrics Served In-Process](https://prometheus-proxy.com/embedded-agent/index.md#metrics-served-in-process) describes. A name with characters the proxy refuses in a path, such as `Order Service`, gives `Order_Service_metrics`. Each run of whitespace, control characters, `?`, `#`, or `/` becomes one `_`, and those at the name's ends are left out. - **An agent named for the app,** `roastery`. With build info, the build's version follows, as in `roastery-1.4.2`, so the proxy's dashboard tells an old deployment from a new one. `spring-boot-maven-plugin`'s `build-info` goal, or `springBoot { buildInfo() }` in Gradle, makes the build info. - **A `prometheusAgent` health component,** with Actuator. It's UP while the agent is connected, with the agent's name and the proxy it reached, and UNKNOWN while it's off or reconnecting. It's never DOWN, so a proxy that's away doesn't take the app out of a load balancer or have it restarted. `management.health.prometheusagent.enabled: false` leaves it out. - **An app that runs without an agent that can't start.** The agent logs why and stays off: a setting it rejects, such as an unreadable certificate, doesn't stop the app. To have the app fail to start instead, also when there's no proxy, set `required: true`. To be told why, have a customizer add an `onFailure` handler ([below](#customizing-in-code)). Each property can also come straight from the environment, by Spring Boot's rules: `PROMETHEUSPROXY_AGENT_PROXY` sets `prometheus-proxy.agent.proxy`. As with any embedded agent, the agent's environment variables, such as `AGENT_TOKEN` or `PROXY_HOSTNAME`, take precedence over its settings, and `PROXY_HOSTNAME` alone starts the agent. Give the app's variables other names, as the example above does. ## See the First Scrape Start the app with `PROMETHEUS_PROXY=localhost:50051` in its environment, for a proxy on the same machine. Spring Boot's web server listens on 8080 by default, as the proxy's scrape port does, so on one machine, give the app another, such as with `SERVER_PORT=8081`. Once the app has started, the agent logs, through the app's [logging](https://prometheus-proxy.com/embedded-debugging/index.md#logging), when it has connected and registered the path: ``` { .text .pp-output .pp-output--ok title="The app's log" } Connected to proxy at localhost:50051 using plaintext Registered in-process as /roastery_metrics with labels {} (static) ``` Without a proxy, the starter logs `No proxy is set (prometheus-proxy.agent.proxy or PROXY_HOSTNAME), so the Prometheus agent stays off` instead. Scrape the path through the proxy, as Prometheus will: ```bash curl -i http://localhost:8080/roastery_metrics ``` ``` { .text .pp-output .pp-output--ok title="curl's output, in part" } HTTP/1.1 200 OK Content-Type: text/plain; version=0.0.4; charset=utf-8 # HELP jvm_threads_live_threads The current number of live threads including both daemon and non-daemon threads # TYPE jvm_threads_live_threads gauge jvm_threads_live_threads 30.0 ``` The body is the app's `PrometheusRegistry` bean, read in-process: Spring Boot's JVM and process metrics, and the app's own meters, as `/actuator/prometheus` would serve them. 404 Not Found means no agent has registered the path. Check the app's log for the `Registered` line; [Debugging an Embedded Agent](https://prometheus-proxy.com/embedded-debugging/index.md) shows where else to look. Then give Prometheus a job for the path, with the proxy's host in place of `localhost` where Prometheus runs elsewhere, and have it read the job: ```yaml scrape_configs: - job_name: 'roastery' metrics_path: '/roastery_metrics' static_configs: - targets: ['localhost:8080'] ``` !!! success "You're done when Prometheus shows `roastery` up" After Prometheus's next scrape, its target page (Status → Target health) shows `roastery` as up: Prometheus is scraping the app's registry, in-process, through the proxy. ## Properties Each is under `prometheus-proxy.agent`, and an IDE completes and describes them from the starter's metadata. | Property | Default | What it sets | |----------------------------|----------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `proxy` | | The proxy, as `host` or `host:port` (the port defaults to 50051), or several, separated by commas, in the order the agent fails over through them. Unset, the agent stays off, unless a customizer, a `settings` key, or `PROXY_HOSTNAME` names one | | `token` | | The token the agent presents to the proxy, which has to match the proxy's | | `trust-certificate` | | The certificate the agent trusts the proxy's by, as PEM text or its base64, which turns [TLS](https://prometheus-proxy.com/security/tls/index.md) on | | `authority` | | The name the proxy's certificate was issued to, when it isn't the host the agent connects to; used with `trust-certificate` | | `client-certificate` | | The agent's certificate chain, as PEM text or its base64, for a proxy that requires mutual TLS | | `client-key` | | The private key of `client-certificate`, as PEM text or its base64 | | `name` | the app's name and build version | The agent's name, as the proxy's dashboard and logs show it; `Unnamed-` and the host without `spring.application.name` | | `path` | the app's name, then `_metrics` | The proxy's path the app's metrics are served at; `application_metrics` without `spring.application.name`. Since 4.8.0, the name's whitespace, control characters, `?`, `#`, and `/` become `_`, a run of them one, so `Order Service` gives `Order_Service_metrics` | | `labels.` | | The labels of the app's path, in the proxy's [service discovery](https://prometheus-proxy.com/service-discovery/index.md) | | `source` | `registry` | `registry` serves the app's `PrometheusRegistry` bean; `none` serves only `paths` and what a customizer adds | | `paths[n].path`, `.url` | | Another target the agent scrapes over HTTP, served at a separate path, with `.username`, `.password`, and `.labels.`; an entry without a path or a URL fails the agent's start | | `consolidated` | `false` | Whether the agent registers its paths in [consolidated mode](https://prometheus-proxy.com/advanced/index.md#consolidated-mode), alongside other agents serving them | | `metrics-port` | | The port of the agent's own metrics, which are off without one, for a scraper on the app's network ([Port or Proxy Path](https://prometheus-proxy.com/monitoring/index.md#port-or-proxy-path)) | | `metrics-proxy-path` | | The proxy's path the [agent's own metrics](https://prometheus-proxy.com/embedded-agent/index.md#the-agents-own-metrics) are served at, read in-process, with no port; off without one. They stay apart from the app's path, whose JVM metrics they'd repeat | | `metrics-proxy-path-labels.` | | The labels of `metrics-proxy-path`, in the proxy's [service discovery](https://prometheus-proxy.com/service-discovery/index.md) | | `dashboard.port`, `.host` | | The agent's direct [dashboard](https://prometheus-proxy.com/agent-dashboard/index.md), off without a port, listening on every interface unless `host` names one, such as `127.0.0.1` | | `dashboard.password` | | Requires a login to the direct dashboard, as `dashboard.username` (`admin` by default) | | `required` | `false` | Whether the app fails to start when the agent can't, or has no proxy | | `stop-timeout` | `30s` | Since 4.8.0, how long the app's shutdown waits for the agent's stop, more than zero, as a number of seconds or a duration such as `10s` or `PT10S`; once it's up, the app stops anyway, and the agent goes on stopping | | `settings.` | | Any other [agent setting](https://prometheus-proxy.com/configuration/agent/index.md), by its key under `agent`, such as `settings.scrapeTimeoutSecs: 20`. It takes precedence over the properties above | | `enabled` | `true` | Whether to run the agent at all | A `settings` key keeps its case only in a properties or YAML file: Spring Boot lowercases one read from an environment variable, which then names no setting. A proxy with agent screens on shows the agent's relayed dashboard on its screens page, whether or not `dashboard.port` turns its direct dashboard on. The proxy reaches it through the agent's connection, and shows it to everyone who can sign in to the proxy's dashboard ([Showing It as a Relayed Agent Dashboard](agent-dashboard.md#showing-it-on-the-proxy)); [Direct and Relayed Agent Dashboards](agent-dashboard.md#direct-and-relayed-agent-dashboards) compares the two. To keep the app's agent off every proxy's screens page, set `prometheus-proxy.agent.settings.dashboard.showOnProxy` to `false` in a properties or YAML file. ## Customizing in Code For what properties can't hold, such as a certificate the app reads from a secret store, or a registry that isn't a bean, add a `PrometheusProxyAgentCustomizer` bean. It's given the agent's [`EmbeddedAgentConfig.Builder`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentconfig) once the properties are applied, just before the agent starts. Several customizers run in their `@Order`, each after the one before. A builder method a customizer calls replaces what a property set. A `settings.` property is the exception: it takes precedence over the builder's methods, as anything `setting()` sets does, so change one with `setting()` and its key. The starter decides whether to start the agent once the customizers have run, so a customizer can give it its proxy, as `fromEnvironment()` does. Since 4.8.0, a customizer can also add an `onFailure` handler, such as `builder.onFailure((reason, e) -> alerts.send(reason))`. It's told why an agent that isn't `required` couldn't start, as the log gives it, so the app can report it somewhere else too. That includes a property the builder can't take, such as a `stop-timeout` of zero, and a customizer that throws. The starter runs every customizer whatever failed, so each one's handler is added before they're told. ```java import io.prometheus.agent.spring.PrometheusProxyAgentCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class AgentCustomizations { // What properties can't hold: the proxy's certificate, read from the app's secret store as the agent starts, a // registry of the app's own, which isn't a bean, served at a path of its own, and who hears why an agent couldn't // start, which stays off while the app runs on @Bean PrometheusProxyAgentCustomizer agentCustomizer(SecretStore secrets, BatchJobs batchJobs, Alerts alerts) { return builder -> builder .trustCertificatePem(secrets.read("prometheus-proxy-ca"), "prometheus-proxy") .source("batch_jobs_metrics", batchJobs.registry()) .onFailure((reason, e) -> alerts.send("No metrics from this app: " + reason)); } } ``` The agent is the `PrometheusProxyAgent` bean. Its `agent()` gives the running agent's [`EmbeddedAgentInfo`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo), or nothing while it's off. An app's own `PrometheusProxyAgent` bean takes the place of the starter's, and has the health component. An app with more than one has no health component, since it couldn't choose between them. ## Spring Boot's Versions of the Agent's Libraries Spring Boot's dependency management sets the versions of the libraries it knows, some of the agent's among them, and some of those are older than the agent's own. The agent runs with Spring Boot 4.2's, and with 4.0's and 4.1's once the two [above](#adding-the-dependency) are set. The starter's tests run it at 4.2's, and at 4.0's last release's with those two set. The [Spring Boot Demo](https://prometheus-proxy.com/spring-boot-demo/index.md#spring-boots-versions-of-the-agents-libraries) runs it at 4.2's, and its `./demo.sh versions` shows which are older. Were a Spring Boot release to break the agent, set that library to the agent's version in the app's pom. Use the property Spring Boot names it by, such as `kotlin-coroutines.version`, `prometheus-client.version`, `grpc-java.version`, or `netty.version`; Spring Boot's [Version Properties](https://docs.spring.io/spring-boot/appendix/dependency-versions/properties.html) lists one for every library it manages. netty-tcnative has none, since Netty's BOM sets it: pin `netty-tcnative-classes` and `netty-tcnative-boringssl-static`, with each native's classifier, in the pom's `dependencyManagement`. ## Without the Starter An app can wire the agent itself, with the builder from [Configuring in Code](https://prometheus-proxy.com/embedded-agent/index.md#configuring-in-code) and a few beans. Each of these does part of what the starter does: - **Start and stop it from a `SmartLifecycle` bean** in the last phase, the default. The agent then starts once the web server is serving, so its first scrape finds the app's metrics. It stops first on shutdown, before the web server drains: the agent disconnects, the proxy drops its paths, and no scrape reaches a server that's going away. - **Read the app's metrics in-process,** with `source` and the app's `PrometheusRegistry` bean ([Metrics Served In-Process](https://prometheus-proxy.com/embedded-agent/index.md#metrics-served-in-process)). `/actuator/prometheus` then needn't be exposed at all. - **Or scrape Actuator's endpoint.** With `micrometer-registry-prometheus` on the classpath, add `prometheus` to `management.endpoints.web.exposure.include`, which exposes only `health` by default. Actuator then serves the metrics at `/actuator/prometheus`: give `scrapeSelf` `"actuator/prometheus"` as its `metricsPath`, with the credentials the app's Spring Security asks for. - **Hold the settings in a `@ConfigurationProperties` record,** with `application.yml` reading each from the environment, as `${PROMETHEUS_AGENT_TOKEN:}` does. Give it a `toString` that leaves the secrets out, so the app can log it. - **Set the library versions** the agent needs on Spring Boot 4.0 or 4.1, as [above](#adding-the-dependency), and read [Spring Boot's Versions of the Agent's Libraries](#spring-boots-versions-of-the-agents-libraries). - **Report the agent in `/actuator/health`** with a health indicator, from `EmbeddedAgentInfo.isConnected` and `proxyEndpoint`. Report UP while it's connected, and UNKNOWN, not DOWN, while it's off or reconnecting, so a lost proxy leaves the app's health UP. - **Configure its logging** in the app's, as [Logging](https://prometheus-proxy.com/embedded-debugging/index.md#logging) describes. --- Source: https://prometheus-proxy.com/embedded-api/ # Embedded Agent API The methods and types an application that [embeds the agent](https://prometheus-proxy.com/embedded-agent/index.md) calls, with what each takes, returns, and throws. ## `Agent.startAsyncAgent()` Starts the agent in the background, on a daemon thread, and returns once it has started (see [`EmbeddedAgentInfo`](#embeddedagentinfo) for how long it runs). | Parameter | Type | Description | |:----------------------|:----------|:-----------------------------------------------------------------------------------------------------------------------------------------| | `configFilename` | `String` | Path to the HOCON config file | | `exitOnMissingConfig` | `Boolean` | Pass `false` to embed: a config error or invalid option throws `ConfigLoadException`. `true` exits the JVM, as the standalone agent does | | `logBanner` | `Boolean` | Log the startup banner (default: `true`, which Java callers get by leaving it out too) | Or, to start the agent from a config built in memory (see [A `Config` of Your Own](https://prometheus-proxy.com/embedded-agent/index.md#a-config-of-your-own)): | Parameter | Type | Description | |:------------|:----------|:----------------------------------------------------------------------------------------------------| | `config` | `Config` | The agent's configuration, rooted at `agent`, as a Typesafe `Config` | | `logBanner` | `Boolean` | Log the startup banner (default: `true`, which Java callers get by leaving it out too) | This form is always embedded: a config error throws `ConfigLoadException`, and never exits the JVM. **Returns:** `EmbeddedAgentInfo` **Throws:** `ConfigLoadException`, when `exitOnMissingConfig` is `false` or the config is in memory, for a config that can't be loaded or parsed, or for a setting the agent can't use, from the config or an environment variable: - a value of the wrong type or out of range, such as `scrapeTimeoutSecs = "abc"` or `0`; - an unresolved `${…}` substitution; - a malformed proxy endpoint; - a duplicate `pathConfigs` or `filters` entry, or a filter regex that doesn't compile; - an HTTPS trust store (`agent.http.trustStorePath`) or TLS certificate file that is missing, unreadable, or malformed, or a TLS certificate or key given as PEM that can't be read, or given as both a file and PEM. Credentials in a config URL are redacted from its message and from every message in its cause chain. The cause is the exception that rejected the setting, usually an `IllegalArgumentException`. When that exception's message held a URL with credentials, as a Typesafe `ConfigException`'s does for a value read from a config URL, the cause is a stand-in `ConfigLoadException` with the redacted message and the original stack trace. `IllegalStateException` when the agent fails to start (for example, its admin, metrics, or dashboard port is already in use), with the startup failure as its cause, or doesn't start within 30 seconds, with a `TimeoutException` as its cause. A failed start releases everything the agent had opened, and an agent still starting when the wait ends stops as soon as its startup does, without connecting. Also, before the agent is built, when the app's dependency management sets kotlinx-coroutines below 1.11.0 or the Prometheus Java client below 1.7.0, as Spring Boot 4.0 and 4.1 do ([Spring Boot Starter](https://prometheus-proxy.com/spring-boot-starter/index.md#adding-the-dependency)): its message names the Spring Boot property that sets each. ## `EmbeddedAgentConfig` An embedded agent's settings, built in code (see [Configuring in Code](https://prometheus-proxy.com/embedded-agent/index.md#configuring-in-code)). From Kotlin, `embeddedAgent { … }` builds one, its block calling the builder's methods; from Java, `EmbeddedAgentConfig.builder()` returns the builder, whose methods chain and end with `build()`. A method called twice keeps its last value, and `scrapeSelf`, `path`, and `source` add a path each time, and `onFailure` a handler. | Builder method | Sets | Description | |:-------------------------------------------------------------------|:----------------------------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------| | `name(name)` | `agent.name` | The agent's name, as the proxy's dashboard and logs show it | | `proxy(endpoints…)` | `agent.proxy.endpoints` | The proxy's agent port, as `host` or `host:port` (the port defaults to 50051), or several, in the order the agent fails over through them | | `token(token)` | `agent.agentToken` | The token the agent presents to the proxy | | `trustCertificatePem(pem, authority)` | `agent.tls.trustCertCollectionPem`, `agent.tls.overrideAuthority` | The certificate the agent trusts the proxy's by, as PEM or its base64, which turns TLS on, and, optionally, the name the proxy's certificate was issued to | | `clientCertificatePem(certChainPem, privateKeyPem)` | `agent.tls.certChainPem`, `agent.tls.privateKeyPem` | The agent's certificate chain and key, as PEM or its base64, for a proxy that requires mutual TLS | | `fromEnvironment()` | `proxy`, `token`, `trustCertificatePem`'s | Since 4.7.0, set them from `PROMETHEUS_PROXY`, `PROMETHEUS_AGENT_TOKEN`, `PROMETHEUS_PROXY_CERT`, and `PROMETHEUS_PROXY_AUTHORITY`, those set ([Settings From the Environment](https://prometheus-proxy.com/embedded-agent/index.md#settings-from-the-environment)) | | `consolidated(consolidated)` | `agent.consolidated` | Register the agent's paths in consolidated mode; `consolidated()` alone turns it on | | `agentMetrics(port)` | `agent.metrics.enabled`, `agent.metrics.port` | Turn on the agent's own metrics endpoint, which is off unless asked for | | `agentMetricsAt(path, labels)` | `agent.metrics.proxyPath`, `agent.metrics.proxyPathLabels` | Since 4.7.0, serve the agent's own metrics at `path`, read in-process, with no port ([Agent's Metrics](https://prometheus-proxy.com/embedded-agent/index.md#the-agents-own-metrics)); `labels` is optional | | `dashboard(port, host)` | `agent.dashboard.enabled`, `agent.dashboard.port`, `agent.dashboard.host` | Since 4.7.0, turn on the agent's direct [dashboard](https://prometheus-proxy.com/agent-dashboard/index.md), on a separate port, which is off unless asked for; `host`, such as `127.0.0.1`, is optional | | `dashboardLogin(password, username)` | `agent.dashboard.password`, `agent.dashboard.username` | Since 4.7.0, require a login to the agent's direct dashboard; `username` defaults to `admin` | | `scrapeSelf(path, port, username, password, metricsPath, labels)` | `agent.pathConfigs` | Scrape the app at `http://127.0.0.1:/` (default `metrics`) and serve it at `path`; the rest are optional | | `path(path, url, username, password, labels)` | `agent.pathConfigs` | Scrape any target at `url` and serve it at `path`; the rest are optional, and the URL then carries no credentials | | `source(path, registry)`, `source(path, labels, registry)` | none: it's code | Since 4.7.0, serve the `PrometheusRegistry` at `path`, read in-process ([Metrics Served In-Process](https://prometheus-proxy.com/embedded-agent/index.md#metrics-served-in-process)), with the path's labels or none | | `source(path, source)`, `source(path, labels, source)` | none: it's code | Since 4.7.0, serve what the `MetricsSource` writes at `path`, read in-process, with the path's labels or none | | `setting(key, value)` | the key, under `agent` | Any other setting, such as `http.clientTimeoutSecs`; it takes precedence over a method that sets the same key | | `onFailure(handler)` | none: it's code | Since 4.8.0, add a handler `startIfConfigured()` tells of a start that fails, with why and what was thrown ([Starting Where There's a Proxy](https://prometheus-proxy.com/embedded-agent/index.md#starting-where-theres-a-proxy)) | | `reportFailure(cause)` | none: it's an action | Since 4.8.0, log a failure that came while the settings were being made, before the agent could start, and tell the `onFailure` handlers, as a failed start does, for a host that makes the settings from its configuration ([Starting Where There's a Proxy](https://prometheus-proxy.com/embedded-agent/index.md#starting-where-theres-a-proxy)) | | `stopTimeout(timeout)` | none: it's the handle's | Since 4.8.0, how long the handle's `shutdown()` waits for the agent to stop, more than zero, or `Duration.INFINITE` for as long as it takes; `null`, the default, leaves the wait to the agent's stop, 30 seconds ([`EmbeddedAgentInfo`](#embeddedagentinfo)) | In `embeddedAgent { }`, `name`, `proxy`, `token`, `consolidated`, `agentMetricsPort`, `dashboardPort`, and `stopTimeout` are properties too, so `name = "my-app"` does what `name("my-app")` does; `proxy` takes several endpoints separated by commas, as `PROXY_HOSTNAME` does, `stopTimeout` takes a Kotlin `Duration`, where its method takes a `java.time.Duration`, and `null` takes `name`, `proxy`, `token`, `agentMetricsPort`, `dashboardPort`, or `stopTimeout` out. Java sees only the methods. A username and password are percent-encoded into the URL and sent as Basic Auth; both empty, as unset environment variables give, means none. Labels are a map of names to values. A value the builder can tell is wrong, such as a blank path, `/` alone, a path of more than one segment (`app/metrics` or `//metrics`), a blank URL, or a port out of range, throws `ConfigLoadException` as the method is called, as `start()` does for a setting the agent rejects. ??? note "Through 4.7.0" `/` alone and a blank URL passed, and the agent dropped the target at startup with a warning, as it does a config file's placeholder, and a path of more than one segment passed too, and no scrape reached it. | `EmbeddedAgentConfig` member | Type | Description | |:-------------------------------------|:---------------------|:-------------------------------------------------------------------------------------------------------| | `start(logBanner)` | `EmbeddedAgentInfo` | Starts the agent, as `startAsyncAgent(config)` does, and throws as it does; `logBanner` defaults to `true` | | `startIfConfigured(logBanner, onFailure)` | `EmbeddedAgentInfo?` | Since 4.7.0, starts the agent where the settings or `PROXY_HOSTNAME` name a proxy, and returns `null` without one, or for a start that fails, which it logs and tells the builder's `onFailure` handlers, then `onFailure`, optional, with why and what was thrown ([Starting Where There's a Proxy](https://prometheus-proxy.com/embedded-agent/index.md#starting-where-theres-a-proxy)) | | `namesProxy()` | `Boolean` | Since 4.7.0, whether the settings or `PROXY_HOSTNAME` name a proxy, the rule `startIfConfigured()` starts by | | `toConfig()` | `Config` | The settings as the tree a config file holds, rooted at `agent`, without the paths `source` adds, which are code | | `toString()` | `String` | The settings, with the token, passwords, and PEMs shown only as set, a path's credentials masked, and a `source` path as `in-process`, so an app can log them | `MetricsSource.of(registry)`, a static method from Java, is the `MetricsSource` that `source(path, registry)` serves a `PrometheusRegistry` with. ## `EmbeddedAgentInfo` The handle `startAsyncAgent()` and `EmbeddedAgentConfig.start()` return. | Member | Type | Description | |:----------------|:----------|:--------------------------------------------------------------------------------------------------------------------------------------------------| | `launchId` | `String` | Unique ID for this agent launch, new each time an agent starts | | `agentName` | `String` | Name of the agent: `agent.name`, or `Unnamed-` when none is set | | `isConnected` | `Boolean` | Whether the agent is connected to a proxy and has registered its paths there, so Prometheus can scrape through it now; read live, for a health check | | `proxyEndpoint` | `String?` | The proxy it's connected to, as `host:port`, or `null` when it isn't | | `shutdown()` | `Unit` | Stops the agent and blocks until it has stopped, up to the builder's `stopTimeout`, or, without one, 30 seconds, after which it throws an `IllegalStateException`, with the `TimeoutException` as its cause; calling it again, or on a failed agent, does nothing | | `close()` | `Unit` | Since 4.7.0, does what `shutdown()` does: the handle is `AutoCloseable`, for Kotlin's `use` and Java's try-with-resources | `isConnected` is false before the agent's first connection, while it reconnects after losing one, and once it has stopped. A host's health check can report it, though without failing the app's health: a lost proxy shouldn't take the app down. Call `shutdown()` wherever your application stops its services, or from a shutdown hook it adds. It closes the connection to the proxy, drains the scrapes in flight, and releases its admin, metrics, and dashboard ports, so the agent's connection and background work don't outlive your application. It waits up to the builder's `stopTimeout` (since 4.8.0): once that's up, `shutdown()` returns, with a warning in the log, and the agent goes on stopping on a separate daemon thread, so your application's shutdown fits the window its platform gives it, such as the 30 seconds Kubernetes gives a pod, or Cloud Run's 10. A stop that fails within it throws. Without a `stopTimeout`, it waits 30 seconds at most, then throws an `IllegalStateException`, whose cause is a `java.util.concurrent.TimeoutException`, and the agent goes on stopping. An interrupt ends neither wait. Since 4.7.0, the agent registers no JVM shutdown hook, so it stops when your application stops it, after the work that needs it, not at the same time as your application's hooks; the [Ktor Plugin](https://prometheus-proxy.com/ktor-plugin/index.md) and the [Spring Boot Starter](https://prometheus-proxy.com/spring-boot-starter/index.md) stop it with the app. ??? note "Through 4.7.0" Without a `stopTimeout`, `shutdown()` threw the `TimeoutException` itself, which Java code couldn't catch. Since 4.7.0, too, the agent runs on a daemon thread, so it doesn't keep the JVM running: your application's threads do. An application that fails after starting the agent, without stopping it, still exits. So does a program whose `main()` starts the agent and returns, at once, ending the agent without draining its scrapes: keep `main()` running for as long as the agent is needed, as `startIfConfigured().use { worker.run() }` does. With its admin or metrics port on, the agent also runs those ports' servers, whose threads do keep the JVM running until the agent stops. On SIGTERM, the JVM runs its shutdown hooks and exits without returning from `main()`. So a program that runs until it's stopped, as a queue consumer does, adds a hook that ends its work and waits for `main()` to return, by which time `use` has stopped the agent, as the [Plain Kotlin Demo](https://prometheus-proxy.com/plain-kotlin-demo/index.md)'s ovens do. The hook waits 25 seconds at most, so the JVM still exits on its own within the 30 seconds Kubernetes gives a pod to stop, and the agent's `stopTimeout` of 20 seconds keeps its stop inside the hook's wait: === "Kotlin" ```kotlin import io.prometheus.agent.embeddedAgent import kotlin.time.Duration.Companion.seconds fun main(args: Array) { val worker = Worker(args) // On SIGTERM, the JVM runs its shutdown hooks, then exits without returning from main. This one has the worker // finish what it's doing, then waits for main to return, by which time use { } has stopped the agent. It waits 25 // seconds at most, short of the 30 Kubernetes gives a pod to stop. Once it's added, don't call exitProcess() in main: // exitProcess() waits for the hooks, and this one would wait for main until its time is up. val mainThread = Thread.currentThread() Runtime.getRuntime().addShutdownHook( Thread { worker.stop() mainThread.join(25000) }, ) embeddedAgent { // The agent's settings fromEnvironment() // Its stop, as use { } ends, fits inside the hook's 25 seconds stopTimeout = 20.seconds }.startIfConfigured().use { worker.run() } } ``` === "Java" ```java public static void main(String[] args) { Worker worker = new Worker(args); // On SIGTERM, the JVM runs its shutdown hooks, then exits without returning from main. This one has the worker // finish what it's doing, then waits for main to return, by which time try-with-resources has stopped the agent. // It waits 25 seconds at most, short of the 30 Kubernetes gives a pod to stop. Once it's added, don't call // System.exit() in main: System.exit() waits for the hooks, and this one would wait for main until its time is up. Thread mainThread = Thread.currentThread(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { worker.stop(); try { mainThread.join(25000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } })); EmbeddedAgentConfig config = EmbeddedAgentConfig.builder() // The agent's settings .fromEnvironment() // Its stop, as try-with-resources ends, fits inside the hook's 25 seconds .stopTimeout(Duration.ofSeconds(20)) .build(); // Null when the agent stays off, which try-with-resources takes: the worker runs either way try (EmbeddedAgentInfo agent = config.startIfConfigured()) { worker.run(); } } ``` Without the hook, the agent of a `use` block ends with the JVM, without draining the scrapes in flight. Once the hook is added, don't call `exitProcess()` or `System.exit()` in `main()`, as on a fatal error: it waits for the shutdown hooks, and this one waits for `main()`, so the JVM hangs until the hook gives up. To end with an error, throw from `main()` instead: the JVM then exits with status 1. ## `Agent.startSyncAgent()` Starts an agent from command-line arguments, as the standalone agent's `main()` does, and returns once the agent is running. It returns no handle: the agent runs on a non-daemon thread, so a JVM whose `main()` calls this keeps running until the agent stops. Use `startAsyncAgent()` to embed an agent you stop yourself. | Parameter | Type | Description | |:----------------------|:----------------|:---------------------------------------------------------------------------------------------------------------------------------------------| | `args` | `Array` | The agent's [CLI options](https://prometheus-proxy.com/cli-reference/index.md#agent-options), such as `--config agent.conf` | | `exitOnMissingConfig` | `Boolean` | `true` behaves as the standalone agent does, exiting the JVM on a config error. `false` throws `ConfigLoadException` instead, and with no `--config` falls back to the built-in defaults | **Throws:** `ConfigLoadException`, when `exitOnMissingConfig` is `false`, in the cases [`startAsyncAgent()`](#agentstartasyncagent) lists, and for `-v` or `-u`; `IllegalStateException` when the agent fails to start, with the failure as its cause. It waits up to 30 seconds for the agent to start. --- Source: https://prometheus-proxy.com/embedded-debugging/ # Debugging an Embedded Agent Where an [embedded agent](https://prometheus-proxy.com/embedded-agent/index.md) logs, and how to see what it's doing: its admin and debug endpoints, its dashboard, its log, and the proxy's view of it. ## Logging Your application configures the agent's logging. The agent logs through SLF4J, and brings neither an SLF4J provider nor a configuration, so its loggers go wherever your application's do: - **With Logback,** your `logback.xml` (or, in Spring Boot, `logback-spring.xml` and the `logging.level` properties) applies to the agent's loggers as it does to the rest. With no configuration at all, Logback logs everything at DEBUG, gRPC and Netty included. - **With another provider,** such as Log4j2, its configuration applies to them instead. The agent's `logLevel` sets a level only through Logback: with another provider, the agent logs a warning and leaves the level to its configuration. - **With none,** SLF4J prints a warning that it found no provider, and nothing logs, the agent included. Add one, such as `ch.qos.logback:logback-classic`, at runtime. The standalone agent's configuration sets `io.grpc.internal` to WARN, so that only gRPC's internal warnings and errors reach its log; you may want the same: ```xml ``` In Spring Boot, set `logging.level.io.grpc.internal=WARN` instead. ## Admin and Debug Endpoints Start by turning on the agent's admin endpoints and its `/debug` page, which are off unless asked for. The simplest way is the app's environment, which the agent reads itself, with no change to the code: ```bash ADMIN_ENABLED=true # the admin endpoints, on port 8093 (ADMIN_PORT for another) DEBUG_ENABLED=true # adds /debug ``` They take effect at the app's next start, and override the code. So a deployed app turns them on with a restart, and off again once the agent works, with no new build. The builder has no method for them: in code, set them with `setting("admin.enabled", true)`, `setting("admin.port", 8093)`, and `setting("admin.debugEnabled", true)`. In a config file or a `Config`, they're `agent.admin.enabled`, `agent.admin.port`, and `agent.admin.debugEnabled`. The agent then serves these on its admin port, as the standalone agent does: | Path | Shows | |:---------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `/ping` | `pong`, while the agent is running | | `/version` | The agent's version, release date, and build time, as JSON | | `/healthcheck` | The agent's health checks, as JSON: `all_services_healthy`, `scrape_request_backlog_check` (scrape requests waiting for the agent), `thread_deadlock`, `metrics_service` when its metrics port is on, and `dashboard_service` when its dashboard is on | | `/threaddump` | A dump of the JVM's threads, your application's as well as the agent's | | `/debug` | The agent's name, its ID (empty while it isn't connected), the proxy it's connected to or trying, its uptime, its admin and metrics services, each path with the URL it scrapes, credentials masked, and the paths discovery registered or skipped | `/healthcheck` stays healthy while the agent can't reach a proxy, since it reports the agent's state, not its connection: [`EmbeddedAgentInfo`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo)'s `isConnected` and `proxyEndpoint` tell you that. Turn them off once the agent works. The admin port answers on every interface, without authentication, and `/threaddump` shows your application's threads too. While they're on, keep the port on an internal network, as for a standalone agent (see [Production](https://prometheus-proxy.com/production/index.md)). Pick a port your application doesn't use: a port in use makes `start()` throw `IllegalStateException`. The [Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md#debugging-the-agent)'s coffee shop turns them on, and its tour shows each one. ## The Agent's Direct Dashboard { #the-agents-dashboard } The agent's direct [dashboard](https://prometheus-proxy.com/agent-dashboard/index.md), which it serves on a separate port, shows what the admin endpoints and the proxy's dashboard can't: whether the agent is connected, and if not, the last error from each proxy endpoint, and each path, with the proxy's reason for refusing one. A relayed agent dashboard, which a proxy with `proxy.dashboard.agentScreens` on shows through the agent's connection, has the same views, but only while the agent is connected ([Direct and Relayed Agent Dashboards](https://prometheus-proxy.com/agent-dashboard/index.md#direct-and-relayed-agent-dashboards)). To turn the direct one on, set `DASHBOARD_ENABLED=true` in the app's environment, for port 8095 (`DASHBOARD_PORT` for another). In code, `dashboard(port = 8095, host = "127.0.0.1")` does it. Like the admin port, it has no login unless one is set, so keep it on an internal network or on `127.0.0.1`. ## Logs To log the agent's `io.prometheus` loggers at DEBUG, set `setting("logLevel", "debug")` or `AGENT_LOG_LEVEL=debug`. That leaves your application's logging alone (see [Logging](#logging)), where a standalone agent's sets the root logger's level. Even at INFO, the agent logs its settings as it starts, such as `adminEnabled: true`, after the environment variables have taken precedence. So its startup log shows whether one overrode the builder. ## On the Agents Dashboard The [Agents dashboard](https://prometheus-proxy.com/grafana/index.md#dashboards) the project ships shows an embedded agent like any other: its connections to the proxy, its scrapes and their failures, their latency, and its backlog. It reads them from the agent's own metrics, which `agentMetricsAt(path)` serves through the proxy, with no port opened for them (see [Agent's Metrics](https://prometheus-proxy.com/embedded-agent/index.md#the-agents-own-metrics)): === "Kotlin" ```kotlin embeddedAgent { // The agent's other settings agentMetricsAt(path = "my_app_agent_metrics") }.startIfConfigured() ``` === "Java" ```java EmbeddedAgentConfig.builder() // The agent's other settings .agentMetricsAt("my_app_agent_metrics") .build() .startIfConfigured(); ``` Then give the path a separate Prometheus job, since the dashboard tells agents apart by `job`. The [Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md) does this for its coffee shop's agent, and its Grafana links to the dashboard. ## The Proxy's View The proxy's [dashboard](https://prometheus-proxy.com/web-dashboard/index.md) shows whether the agent registered, the paths it holds, and each path's recent scrapes. To scrape a path through the proxy without Prometheus, run `curl -i http://:8080/`. [Troubleshooting](https://prometheus-proxy.com/troubleshooting/index.md) says what each status code and outcome means. --- Source: https://prometheus-proxy.com/embedded-upgrading/ # Upgrading an Embedded Agent What each release since 4.0 changed for code that [embeds the agent](https://prometheus-proxy.com/embedded-agent/index.md), and what to do about it. A release that changed nothing an embedding app sees isn't listed; the [changelog](https://github.com/pambrose/prometheus-proxy/blob/master/CHANGELOG.md) lists every change. For the proxy your app's agent connects to, and the standalone agents beside it, see [Upgrading the Proxy and Agents](https://prometheus-proxy.com/upgrading/index.md), including which versions work together. ## Upgrading from 4.8.0 - An app written in Kotlin needs Kotlin 2.4 or later to compile. The agent, the Ktor plugin, and the Spring Boot starter are built with Kotlin 2.5, and Kotlin 2.3 refuses their classes on the compile classpath, even where the app's code names none of them: `module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 2.5.0, expected version is 2.3.0`. 4.8.0 compiled with Kotlin 2.3. A Java app isn't affected. - The agent logs a WARN at startup for each setting it's given that isn't one, naming the nearest: a key of the `Config` given to `startAsyncAgent`, a `setting()` key, and the Ktor plugin's and the Spring Boot starter's `settings` keys. The Ktor plugin warns the same way about a key of its `prometheus-proxy.agent` section that it doesn't read. Such a setting never had an effect: fix its name. ## Upgrading from 4.7.0 - The agent's relayed [dashboard](https://prometheus-proxy.com/agent-dashboard/index.md#showing-it-on-the-proxy) shows on any proxy with `proxy.dashboard.agentScreens` on, through the agent's connection, whether or not the app turns its direct dashboard on: its paths, target URLs, scrapes, and activity, to everyone who can sign in to that proxy's dashboard. To keep the app's agent off every proxy, call `setting("dashboard.showOnProxy", false)`, or set the Ktor plugin's or the Spring Boot starter's `settings.dashboard.showOnProxy` to `false`. Unless you do, an agent with its direct dashboard off now keeps its activity feed in memory, within `dashboard.activityLogSize`, and refuses to start with a `dashboard.refreshIntervalSecs`, `dashboard.pathHistorySize`, or `dashboard.activityLogSize` that isn't positive; 4.7.0 checked only the last two, and only with the direct dashboard on. - The agent's direct [dashboard](https://prometheus-proxy.com/agent-dashboard/index.md), when it's on, allows framing by default, so any page can show it in a frame, such as a portal's. 4.7.0 refused framing on every dashboard response. To keep refusing it, call `setting("dashboard.framingEnabled", false)`, or set the Ktor plugin's or the Spring Boot starter's `settings.dashboard.framingEnabled` to `false` (see [Exposure](https://prometheus-proxy.com/dashboard-exposure/index.md#exposure)). - `shutdown()` and `close()`, and `Agent.stop()`, throw an `IllegalStateException`, with the `java.util.concurrent.TimeoutException` as its cause, for an agent without a `stopTimeout` that doesn't stop within 30 seconds. Through 4.7.0 they threw the `TimeoutException` itself, which they didn't declare, so Java code couldn't catch it, and a catch of `RuntimeException` missed it. Kotlin code that caught `TimeoutException` there should catch `IllegalStateException` (see [`EmbeddedAgentInfo`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo)). - The Spring Boot starter's stop waits for the agent at most its new `prometheus-proxy.agent.stop-timeout`, 30 seconds by default, then returns, with a warning, and the agent goes on stopping on a separate daemon thread. Through 4.7.0 it waited the agent's 30 seconds, then threw out of `stop()`. Set `stop-timeout` inside the window your platform gives the app to stop (see [Properties](https://prometheus-proxy.com/spring-boot-starter/index.md#properties)). - `startIfConfigured(onFailure)` logs an exception its `onFailure` throws, and still returns `null`, as it does for the handlers the builder's new `onFailure` adds. Through 4.7.0 the exception escaped the call. An app that can't run without its agent should call `start()`, which throws, instead. - An agent refuses a path of more than one segment, such as `app/metrics` or `//metrics`, which no scrape could reach: through 4.7.0 the agent started with it and served nothing there. A `pathConfigs` entry in the config `startAsyncAgent()` is given now fails its start with `ConfigLoadException`, naming the path. The builder's `path()`, `scrapeSelf()`, `source()`, and `agentMetricsAt()` throw it as they're called, before `startIfConfigured()` can catch it. A Ktor plugin or Spring Boot starter path, its `path`, `metrics-proxy-path`, or a `paths` entry's, keeps the agent off, telling the `onFailure` handlers, or fails a `required` agent's app. Give each path one segment, such as `app_metrics`. - The builder's `path()` throws `ConfigLoadException` for a blank URL, and `path()` and `scrapeSelf()` for `/` alone as a path, as they're called. Through 4.7.0 they took them, and the agent skipped the target at startup with only a warning. A Ktor plugin or Spring Boot starter `paths` entry without a `url`, as an unset environment variable leaves it, or with `/` alone as its `path`, therefore keeps the agent off, telling the `onFailure` handlers, or fails a `required` agent's app, where the agent started without that target. Give the entry its URL, or leave it out. A file `path` or `labels` the Ktor plugin can't read, such as `labels = "team=web"` where a section belongs, fails the agent's start in the same way, where it failed `install(PrometheusProxyAgent)`, the agent enabled or not. - An agent refuses to start with a proxy endpoint it can't dial: one with no host, such as `:50051` or `[]`, or with anything but `:port` after a bracketed IPv6 address, such as `[::1]50051`, whether it comes from `proxy()`, `fromEnvironment()`'s `PROMETHEUS_PROXY`, a `setting()`, or `PROXY_HOSTNAME`. `start()` throws `ConfigLoadException`, naming it, and `startIfConfigured()` logs that and returns `null`. Through 4.7.0, as the only or first endpoint, one with no host failed the start with a less clear message; as a later failover entry, it let the agent start and failed each connect that reached it, and `[::1]50051` dialed `[::1]` on the default port. Write the endpoint in full, such as `[::1]:50051`. - A TLS certificate, key, or trust collection file that exists but can't be read, such as one the app's user may not open, and TLS material the agent can't build its TLS context from, fail the start with `ConfigLoadException`, naming the setting, as any setting the agent rejects does. Through 4.7.0 they reached the app as a `FileNotFoundException` or an `SSLException`. Code that caught either there should catch `ConfigLoadException`. ## Upgrading from 4.6.x - The agent no longer brings Logback. Through 4.6.0, `ch.qos.logback:logback-classic` came with it, at runtime scope, and displaced an application's SLF4J provider: Spring Boot failed to start an app on Log4j2, or ignored its Log4j2 configuration. The agent's loggers now go to your application's provider. An application that logged through the Logback the agent brought, with no SLF4J provider of its own, now gets SLF4J's warning that it found none, and no logs, so add Logback to it (see [Logging](https://prometheus-proxy.com/embedded-debugging/index.md#logging)). - The agent reads `DASHBOARD_ENABLED`, `DASHBOARD_PORT`, `DASHBOARD_PATH`, `DASHBOARD_HOST`, `DASHBOARD_USERNAME`, `DASHBOARD_PASSWORD`, and `METRICS_PROXY_PATH` from your application's environment, which through 4.6.0 only the proxy read, or nothing did. If your application sets any of them for its own use, the agent now opens its dashboard, on port 8095 unless `DASHBOARD_PORT` names another, or serves its metrics at that path, and a value it can't parse, such as an empty `DASHBOARD_PORT`, or a dashboard port that's taken, fails its start. - An agent started with `startAsyncAgent()` or `EmbeddedAgentConfig` registers no JVM shutdown hook. Through 4.6.0 it did, and on SIGTERM it stopped at the same time as your application's hooks, in no set order. Stop it with `shutdown()` or `close()` where your application stops its services (see [`EmbeddedAgentInfo`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo)); one that's never stopped ends with the JVM, without draining the scrapes in flight. - An agent started with `startAsyncAgent()` or `EmbeddedAgentConfig` runs on a daemon thread, so it no longer keeps the JVM running. Through 4.6.0 its thread did: an application that failed after starting the agent never exited, and a program whose `main()` only started the agent kept running. That program now exits at once, unless the agent's admin or metrics port is on, whose servers' threads keep the JVM running until the agent stops. Keep `main()` running for as long as the agent is needed, or start the agent as the standalone agent does, with `startSyncAgent()`. - In an application on Spring Boot 4.0 or 4.1, set `kotlin-coroutines.version` to `1.11.0` and `prometheus-client.version` to `1.10.0`: Spring Boot's dependency management sets kotlinx-coroutines and the Prometheus Java client below the versions the agent runs on. The agent now checks both as it starts, and refuses to start with either too old, naming the property to set, where it failed once it ran. Spring Boot 4.2 needs neither (see [Spring Boot Starter](https://prometheus-proxy.com/spring-boot-starter/index.md)). - A JVM `Error`, such as an `OutOfMemoryError`, in the agent's connection to the proxy stops the agent, as one in a scrape already did, and the app runs on without it, with `isConnected` false. Through 4.6.0 it ended only the connection, and the agent reconnected and ran on in whatever state the `Error` left it in. ## Upgrading from 4.4.x - `startAsyncAgent()` throws `ConfigLoadException` for a config that loads but holds a setting the agent can't use, as listed under [`Agent.startAsyncAgent()`](https://prometheus-proxy.com/embedded-api/index.md#agentstartasyncagent). Through 4.4.2 those escaped as an `IllegalArgumentException` or a Typesafe `ConfigException`, and a `ConfigException`'s message began with the config URL, credentials included. Code that caught either should catch `ConfigLoadException`; the `IllegalArgumentException` is now its cause. - The library jar no longer carries a `logback.xml`. Through 4.4.2 it did, and Logback, and Spring Boot ahead of your `logback-spring.xml`, took it for your application's configuration. An application with no Logback configuration of its own now gets Logback's default, which logs everything at DEBUG, so add one (see [Logging](https://prometheus-proxy.com/embedded-debugging/index.md#logging)); one whose configuration was being replaced gets it back. - Maven builds now get Jackson 2.23.0 and netty-tcnative 2.0.86.Final, natives included, through the agent, where they got Jackson 2.12.7 and the 2.0.84.Final natives. A Jackson your build declares itself still wins. - The agent's generated gRPC classes need protobuf-java 4.36.2 or later, which Maven and Gradle builds now resolve through it, where they got 3.25.9. Your code generated by protoc 3.x keeps working on it. A build that pins protobuf-java to 3.x must move the pin to 4.36.2 or later, or the agent fails when it connects, with a `NoClassDefFoundError` for `com.google.protobuf.RuntimeVersion`. ## Upgrading from 4.1.x - The agent moved from the Prometheus Java client 0.x (`io.prometheus:simpleclient` 0.16.0) to 1.x (`io.prometheus:prometheus-metrics-core` 1.9.0), and its metrics now register in the 1.x default registry. A host that serves the 0.x `CollectorRegistry` no longer exposes them. To serve both from one endpoint, serve the 1.x registry and bridge your 0.x metrics into it: add `io.prometheus:prometheus-metrics-simpleclient-bridge`, at the same version as the `prometheus-metrics-core` the agent brings, and call `SimpleclientCollector.builder().register()` once at startup. - `simpleclient` no longer arrives through the agent. If your application relied on getting it that way, declare it yourself. - With the agent's metrics endpoint on, the `_created` series of its counters and histograms are gone (set `IO_PROMETHEUS_EXPORTER_INCLUDE_CREATED_TIMESTAMPS=true` to bring them back), and with the JVM exports on, the JVM memory metrics are renamed (see [JVM Metrics](https://prometheus-proxy.com/monitoring/index.md#jvm-metrics)). ## Upgrading from 4.0.x - `grpc-netty-shaded` no longer arrives through the agent, which uses the unshaded `grpc-netty` transport. If your application relied on getting it that way, declare it yourself. - `startAsyncAgent()` now waits for the agent to start and throws if it fails, where it used to return a handle to an agent that had failed (see [`Agent.startAsyncAgent()`](https://prometheus-proxy.com/embedded-api/index.md#agentstartasyncagent)). - When a config URL's error message has to be redacted, the `ConfigLoadException`'s cause is a stand-in exception with the redacted message and the original stack trace, not Typesafe's `ConfigException`, so code that checks `cause is ConfigException` no longer matches it. --- Source: https://prometheus-proxy.com/reference/ # Reference For looking something up once you know the system: a setting, a term, or a type in the public API.
- [CLI Reference](https://prometheus-proxy.com/cli-reference/index.md) Every setting of the proxy and the agent: its command-line option over its environment variable, its config key, and its default. - [Glossary](https://prometheus-proxy.com/glossary/index.md) The terms the documentation, the logs, and the dashboards use, grouped by topic. - [KDocs](https://prometheus-proxy.com/kdocs/) The API documentation generated from the code, for the public types an app that embeds the agent calls.
--- Source: https://prometheus-proxy.com/cli-reference/ # CLI Reference Each row is one setting: its command-line option over its environment variable, its config key, and its default. An option overrides the variable, which overrides the config file (see [Configuration](https://prometheus-proxy.com/configuration/index.md)). - **Proxy:** [Startup](#proxy-startup), [Ports and Agents](#proxy-ports-and-agents), [Admin and Metrics](#proxy-admin-and-metrics), [Service Discovery](#proxy-service-discovery), [Dashboard](#proxy-dashboard), [TLS](#proxy-tls), [gRPC](#proxy-grpc-options) - **Agent:** [Startup](#agent-startup), [Proxy Connection](#agent-proxy-connection), [Admin and Metrics](#agent-admin-and-metrics), [Dashboard](#agent-dashboard), [Scraping](#agent-scraping), [HTTP Client](#agent-http-client), [HTTP Client Cache](#agent-http-client-cache-options), [TLS](#agent-tls), [gRPC](#agent-grpc-options) - **Both:** [Log Levels](#log-levels), [Validation](#validation), [Dynamic Properties](#dynamic-properties) ## Proxy Options ### Proxy Startup | CLI Option / Env Var | Setting | Default | Description | |:--------------------------------------------------------------------|:-----------------|:--------|:-----------------------------| | `--config, --conf, -c`
`PROXY_CONFIG` | | | Config file path or URL | | `--log_level`
`PROXY_LOG_LEVEL` | `proxy.logLevel` | "info" | Log level | | `--version, -v` | | | Print version info and exit | | `--usage, -u` | | | Print usage message and exit | | `-D` | | | Dynamic property assignment | ### Proxy Ports and Agents | CLI Option / Env Var | Setting | Default | Description | |:--------------------------------------------------------------------------------------------------------------|:--------------------------------|:--------|:----------------------------| | `--port, -p`
`PROXY_PORT` | `proxy.http.port` | 8080 | HTTP listen port | | `--agent_port, -a`
`AGENT_PORT` | `proxy.agent.port` | 50051 | gRPC listen port for agents | | `--agent_token`
`AGENT_TOKEN` | `proxy.agentToken` | "" | Pre-shared agent auth token | | `--tf-disabled, --tf_disabled`
`TRANSPORT_FILTER_DISABLED` | `proxy.transportFilterDisabled` | false | Disable transport filter | | `--ref-disabled, --ref_disabled`
`REFLECTION_DISABLED` | `proxy.reflectionDisabled` | true | Disable gRPC reflection | ### Proxy Admin and Metrics | CLI Option / Env Var | Setting | Default | Description | |:-----------------------------------------------------------------------------|:---------------------------|:--------|:--------------------------| | `--admin, -r`
`ADMIN_ENABLED` | `proxy.admin.enabled` | false | Enable admin endpoints | | `--admin_port, -i`
`ADMIN_PORT` | `proxy.admin.port` | 8092 | Admin listen port | | `--debug, -b`
`DEBUG_ENABLED` | `proxy.admin.debugEnabled` | false | Enable debug servlet | | `--metrics, -e`
`METRICS_ENABLED` | `proxy.metrics.enabled` | false | Enable metrics collection | | `--metrics_port, -m`
`METRICS_PORT` | `proxy.metrics.port` | 8082 | Metrics listen port | ### Proxy Service Discovery | CLI Option / Env Var | Setting | Default | Description | |:--------------------------------------------------------------------------------------------------|:---------------------------------------|:-----------------|:-----------------------------| | `--sd_enabled`
`SD_ENABLED` | `proxy.service.discovery.enabled` | false | Enable service discovery | | `--sd_path`
`SD_PATH` | `proxy.service.discovery.path` | "discovery" | SD endpoint path | | `--sd_target_prefix`
`SD_TARGET_PREFIX` | `proxy.service.discovery.targetPrefix` | "localhost:8080" | SD target (host:port or URL) | ### Proxy Dashboard | CLI Option / Env Var | Setting | Default | Description | |:-------------------------------------------------------------------------------|:---------------------------|:------------|:-----------------------------| | `--dashboard`
`DASHBOARD_ENABLED` | `proxy.dashboard.enabled` | false | Enable operational dashboard | | `--dashboard_port`
`DASHBOARD_PORT` | `proxy.dashboard.port` | 8094 | Dashboard listen port | | `--dashboard_path`
`DASHBOARD_PATH` | `proxy.dashboard.path` | "dashboard" | Dashboard base path | | `--dashboard_host`
`DASHBOARD_HOST` | `proxy.dashboard.host` | "0.0.0.0" | Dashboard listen address | | `DASHBOARD_USERNAME` | `proxy.dashboard.username` | "admin" | Dashboard login's username | | `DASHBOARD_PASSWORD` | `proxy.dashboard.password` | | Dashboard login's password | The dashboard's login settings have no command-line option, so a password never shows in a process listing: a password turns the login on, with the username `admin` unless set (see [Login](https://prometheus-proxy.com/web-dashboard/index.md#login)). ### Proxy TLS | CLI Option / Env Var | Setting | Default | Description | |:-----------------------------------------------------------------------------------------------------------|:----------------------------------------|:--------|:------------------------| | `--cert, -t`
`CERT_CHAIN_FILE_PATH` | `proxy.tls.certChainFilePath` | | TLS cert chain file | | `--key, -k`
`PRIVATE_KEY_FILE_PATH` | `proxy.tls.privateKeyFilePath` | | TLS private key file | | `--trust, -s`
`TRUST_CERT_COLLECTION_FILE_PATH` | `proxy.tls.trustCertCollectionFilePath` | | TLS trust cert file | | `CERT_CHAIN_PEM` | `proxy.tls.certChainPem` | | TLS cert chain, as PEM | | `PRIVATE_KEY_PEM` | `proxy.tls.privateKeyPem` | | TLS private key, as PEM | | `TRUST_CERT_COLLECTION_PEM` | `proxy.tls.trustCertCollectionPem` | | TLS trust certs, as PEM | The `*_PEM` settings take a certificate or key itself, as PEM text or its base64, in place of the matching file, for a platform that passes secrets as environment variables (see [TLS Setup](https://prometheus-proxy.com/security/tls/index.md#certificates-as-environment-variables)). They have no command-line option, so a key never shows in a process listing. ### Proxy gRPC { #proxy-grpc-options } | CLI Option / Env Var | Setting | Default | Description | |:--------------------------------------------------------------------------------------------------------------------------------|:-----------------------------------------|:--------|:--------------------------------------------| | `--handshake_timeout_secs`
`HANDSHAKE_TIMEOUT_SECS` | `proxy.grpc.handshakeTimeoutSecs` | 120 | Handshake timeout (seconds) | | `--keepalive_time_secs`
`KEEPALIVE_TIME_SECS` | `proxy.grpc.keepAliveTimeSecs` | 7200 | Interval between PING frames (seconds) | | `--keepalive_timeout_secs`
`KEEPALIVE_TIMEOUT_SECS` | `proxy.grpc.keepAliveTimeoutSecs` | 20 | Timeout for PING acknowledgment (seconds) | | `--permit_keepalive_without_calls`
`PERMIT_KEEPALIVE_WITHOUT_CALLS` | `proxy.grpc.permitKeepAliveWithoutCalls` | false | Allow keepalive without active streams | | `--permit_keepalive_time_secs`
`PERMIT_KEEPALIVE_TIME_SECS` | `proxy.grpc.permitKeepAliveTimeSecs` | 300 | Min interval between client PINGs (seconds) | | `--max_connection_idle_secs`
`MAX_CONNECTION_IDLE_SECS` | `proxy.grpc.maxConnectionIdleSecs` | INT_MAX | Max idle time for a channel (seconds) | | `--max_connection_age_secs`
`MAX_CONNECTION_AGE_SECS` | `proxy.grpc.maxConnectionAgeSecs` | INT_MAX | Max lifetime for a channel (seconds) | | `--max_connection_age_grace_secs`
`MAX_CONNECTION_AGE_GRACE_SECS` | `proxy.grpc.maxConnectionAgeGraceSecs` | INT_MAX | Grace period after max age (seconds) | ## Agent Options ### Agent Startup | CLI Option / Env Var | Setting | Default | Description | |:--------------------------------------------------------------------|:-----------------|:--------|:-----------------------------------| | `--config, --conf, -c`
`AGENT_CONFIG` | | | Config file path or URL (required) | | `--name, -n`
`AGENT_NAME` | `agent.name` | | Agent name | | `--log_level`
`AGENT_LOG_LEVEL` | `agent.logLevel` | "info" | Log level | | `--version, -v` | | | Print version info and exit | | `--usage, -u` | | | Print usage message and exit | | `-D` | | | Dynamic property assignment | ### Agent Proxy Connection | CLI Option / Env Var | Setting | Default | Description | |:--------------------------------------------------------------------------------------------------------------|:--------------------------------|:------------|:----------------------------------------------------| | `--proxy, -p`
`PROXY_HOSTNAME` | `agent.proxy.hostname` | "localhost" | Proxy host[:port], or comma-separated failover list | | `--agent_token`
`AGENT_TOKEN` | `agent.agentToken` | "" | Pre-shared token presented to proxy | | `--tf-disabled, --tf_disabled`
`TRANSPORT_FILTER_DISABLED` | `agent.transportFilterDisabled` | false | Disable transport filter | | `--consolidated, -o`
`CONSOLIDATED` | `agent.consolidated` | false | Allow multiple agents per path | `--proxy` and `PROXY_HOSTNAME` replace `agent.proxy.endpoints`; with neither set, the agent reads that list, and reads `agent.proxy.hostname` only when it's empty (see [Proxy failover](https://prometheus-proxy.com/configuration/agent/index.md#proxy-failover)). ### Agent Admin and Metrics | CLI Option / Env Var | Setting | Default | Description | |:-----------------------------------------------------------------------------------------|:---------------------------|:--------|:------------------------------------------------| | `--admin, -r`
`ADMIN_ENABLED` | `agent.admin.enabled` | false | Enable admin endpoints | | `--admin_port, -i`
`ADMIN_PORT` | `agent.admin.port` | 8093 | Admin listen port | | `--debug, -b`
`DEBUG_ENABLED` | `agent.admin.debugEnabled` | false | Enable debug servlet | | `--metrics, -e`
`METRICS_ENABLED` | `agent.metrics.enabled` | false | Enable metrics collection | | `--metrics_port, -m`
`METRICS_PORT` | `agent.metrics.port` | 8083 | Metrics listen port | | `--metrics_proxy_path`
`METRICS_PROXY_PATH` | `agent.metrics.proxyPath` | "" | Proxy path for the agent's own metrics, no port | `--metrics_proxy_path` (since 4.7.0) has the agent serve its own metrics through the proxy at that path, read in-process, with or without the metrics port; its labels, `agent.metrics.proxyPathLabels`, have no command-line option or variable (see [Monitoring](https://prometheus-proxy.com/monitoring/index.md#port-or-proxy-path)). ### Agent Dashboard | CLI Option / Env Var | Setting | Default | Description | |:-------------------------------------------------------------------------------|:---------------------------|:------------|:---------------------------------| | `--dashboard`
`DASHBOARD_ENABLED` | `agent.dashboard.enabled` | false | Enable the agent's direct dashboard | | `--dashboard_port`
`DASHBOARD_PORT` | `agent.dashboard.port` | 8095 | Agent dashboard listen port | | `--dashboard_path`
`DASHBOARD_PATH` | `agent.dashboard.path` | "dashboard" | Agent dashboard base path | | `--dashboard_host`
`DASHBOARD_HOST` | `agent.dashboard.host` | "0.0.0.0" | Agent dashboard listen address | | `DASHBOARD_USERNAME` | `agent.dashboard.username` | "admin" | Agent dashboard login's username | | `DASHBOARD_PASSWORD` | `agent.dashboard.password` | | Agent dashboard login's password | As for the proxy, the dashboard's login settings have no command-line option (see [Agent Dashboard](https://prometheus-proxy.com/agent-dashboard/index.md)). The `DASHBOARD_*` variables have the same names as the proxy's, and each process reads them for its dashboard, as with `ADMIN_*` and `METRICS_*`. ### Agent Scraping | CLI Option / Env Var | Setting | Default | Description | |:----------------------------------------------------------------------------------|:----------------------------|:--------|:---------------------------------------| | `--timeout`
`SCRAPE_TIMEOUT_SECS` | `agent.scrapeTimeoutSecs` | 15 | Scrape timeout (seconds) | | `--max_retries`
`SCRAPE_MAX_RETRIES` | `agent.scrapeMaxRetries` | 0 | Max scrape retries (0 = disabled) | | `--chunk`
`CHUNK_CONTENT_SIZE_KBS` | `agent.chunkContentSizeKbs` | 32 | Chunking threshold (KB, max 4032) | | `--gzip`
`MIN_GZIP_SIZE_BYTES` | `agent.minGzipSizeBytes` | 512 | Min size for gzip (bytes, max 4128768) | ### Agent HTTP Client | CLI Option / Env Var | Setting | Default | Description | |:----------------------------------------------------------------------------------------------------------------|:--------------------------------------------|:--------|:------------------------------| | `--trust_all_x509`
`TRUST_ALL_X509_CERTIFICATES` | `agent.http.enableTrustAllX509Certificates` | false | Disable SSL verification | | `--https_truststore`
`HTTPS_TRUST_STORE_PATH` | `agent.http.trustStorePath` | "" | Trust store for HTTPS targets | | `--https_truststore_password`
`HTTPS_TRUST_STORE_PASSWORD` | `agent.http.trustStorePassword` | "" | Password for the trust store | | `--max_concurrent_clients`
`MAX_CONCURRENT_CLIENTS` | `agent.http.maxConcurrentClients` | 1 | Max parallel scrapes | | `--client_timeout_secs`
`CLIENT_TIMEOUT_SECS` | `agent.http.clientTimeoutSecs` | 90 | HTTP client timeout (seconds) | | `--max_content_length_mbytes` | `agent.http.maxContentLengthMBytes` | 10 | Max response size (MB) | ### Agent HTTP Client Cache { #agent-http-client-cache-options } | CLI Option / Env Var | Setting | Default | Description | |:-------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------|:--------|:----------------------------------------| | `--max_cache_size`
`MAX_CLIENT_CACHE_SIZE` | `agent.http.clientCache.maxSize` | 100 | Max cached HTTP clients | | `--max_cache_age_mins`
`MAX_CLIENT_CACHE_AGE_MINS` | `agent.http.clientCache.maxAgeMins` | 30 | Max age of cached clients (minutes) | | `--max_cache_idle_mins`
`MAX_CLIENT_CACHE_IDLE_MINS` | `agent.http.clientCache.maxIdleMins` | 10 | Max idle time before eviction (minutes) | | `--cache_cleanup_interval_mins`
`CLIENT_CACHE_CLEANUP_INTERVAL_MINS` | `agent.http.clientCache.cleanupIntervalMins` | 5 | Cleanup interval (minutes) | ### Agent TLS | CLI Option / Env Var | Setting | Default | Description | |:-----------------------------------------------------------------------------------------------------------|:----------------------------------------|:--------|:------------------------| | `--cert, -t`
`CERT_CHAIN_FILE_PATH` | `agent.tls.certChainFilePath` | | TLS cert chain file | | `--key, -k`
`PRIVATE_KEY_FILE_PATH` | `agent.tls.privateKeyFilePath` | | TLS private key file | | `--trust, -s`
`TRUST_CERT_COLLECTION_FILE_PATH` | `agent.tls.trustCertCollectionFilePath` | | TLS trust cert file | | `CERT_CHAIN_PEM` | `agent.tls.certChainPem` | | TLS cert chain, as PEM | | `PRIVATE_KEY_PEM` | `agent.tls.privateKeyPem` | | TLS private key, as PEM | | `TRUST_CERT_COLLECTION_PEM` | `agent.tls.trustCertCollectionPem` | | TLS trust certs, as PEM | | `--override, --over`
`OVERRIDE_AUTHORITY` | `agent.tls.overrideAuthority` | | TLS authority override | As for the proxy, the `*_PEM` settings take a certificate or key as PEM text or its base64, and have no command-line option. ### Agent gRPC { #agent-grpc-options } | CLI Option / Env Var | Setting | Default | Description | |:------------------------------------------------------------------------------------------------------------|:-----------------------------------|:--------|:------------------------------------------| | `--keepalive_time_secs`
`KEEPALIVE_TIME_SECS` | `agent.grpc.keepAliveTimeSecs` | INT_MAX | Interval between PING frames (seconds) | | `--keepalive_timeout_secs`
`KEEPALIVE_TIMEOUT_SECS` | `agent.grpc.keepAliveTimeoutSecs` | 20 | Timeout for PING acknowledgment (seconds) | | `--keepalive_without_calls`
`KEEPALIVE_WITHOUT_CALLS` | `agent.grpc.keepAliveWithoutCalls` | false | Allow keepalive without active streams | | `--unary_deadline_secs`
`UNARY_DEADLINE_SECS` | `agent.grpc.unaryDeadlineSecs` | 30 | Timeout for unary RPCs (seconds) | ## Log Levels Available log levels for both proxy and agent: `trace`, `debug`, `info`, `warn`, `error`, `off` The deprecated `all` level was removed in 3.2.0: use `trace` for the most verbose output. ## Validation Options are checked at startup, and an invalid value stops the process with a message naming it, rather than an opaque bind or builder error: - **Ports:** the proxy's `--port` and `--agent_port`, and `--admin_port`, `--metrics_port`, and `--dashboard_port`, must be in `1..65535`. - **The agent's scrape timeout:** `--timeout`, or `agent.scrapeTimeoutSecs`, must be more than `0`. - **gRPC keepalive timeouts:** each must be `-1`, which leaves gRPC's default, or more than `0`. ## Dynamic Properties Use `-D` to set any scalar configuration value. It overrides the config file, but a CLI option or environment variable for the same setting overrides it: ```bash java -jar prometheus-proxy.jar \ -Dproxy.http.port=9090 \ -Dproxy.admin.enabled=true \ -Dproxy.metrics.enabled=true java -jar prometheus-agent.jar \ -Dagent.proxy.hostname=myproxy.com \ -Dagent.http.maxConcurrentClients=5 \ --config agent.conf ``` --- Source: https://prometheus-proxy.com/glossary/ # Glossary The terms the documentation, the logs, and the dashboards use, grouped by topic. ## The Proxy and the Agent ### Agent The component that runs **inside** the firewall, next to the services it monitors. It opens an outbound gRPC connection to the proxy, receives scrape requests over it, fetches each path's [target URL](#target-url), and streams the responses back. See [Agent Configuration](https://prometheus-proxy.com/configuration/agent/index.md). ### Embedded Agent An agent run inside another JVM application rather than as a standalone process, started with `embeddedAgent { }` or `startAsyncAgent()`, or by the [Spring Boot Starter](https://prometheus-proxy.com/spring-boot-starter/index.md) or the [Ktor Plugin](https://prometheus-proxy.com/ktor-plugin/index.md). It can serve the app's metrics registry in-process, with no URL to scrape. See [Embedded Agent](https://prometheus-proxy.com/embedded-agent/index.md). ### `launch_id` An identifier each agent instance gets when it starts, attached as a label to agent metrics, so a Prometheus target can tell an agent's series from those of its previous run, and from those of other agents embedded in the same JVM. See [Monitoring](https://prometheus-proxy.com/monitoring/index.md#agent-metrics). ### Proxy The component that runs **outside** the firewall, alongside Prometheus. It accepts agent connections on its gRPC port (`50051`) and serves the agents' paths to Prometheus on its HTTP port (`8080`). See [Architecture](https://prometheus-proxy.com/architecture/index.md). ## Paths and Scrapes ### Chunking Splitting a large scrape response into several `ChunkedScrapeResponse` messages to stay within gRPC message limits, once its gzipped size reaches `agent.chunkContentSizeKbs` (default 32 KB). See [Architecture](https://prometheus-proxy.com/architecture/index.md#chunking). ### Consolidated Mode A mode (`agent.consolidated = true`) in which several agents serve the **same** path, and the proxy merges their answers to each scrape, instead of the later registration [taking the path over](#takeover). See [Consolidated Mode](https://prometheus-proxy.com/advanced/index.md#consolidated-mode). ### Metric Filter An optional per-path set of allow and deny rules (`agent.filters`) applied at the agent, which drops whole metric families before a payload is compressed and sent to the proxy. Its regexes are fully anchored, and a family's `_bucket`, `_sum`, and `_count` series are kept or dropped together. See [Metric Filtering](https://prometheus-proxy.com/configuration/agent/index.md#metric-filtering). ### Path A single URL path segment an agent registers with the proxy, such as `app1_metrics`. Prometheus scrapes `http://proxy-host:8080/`, the path being its `metrics_path`, and the proxy routes the request to the agent that registered the path. A path must be a **single segment**: one with an embedded `/`, such as `app/metrics`, is refused at registration, as is one with whitespace, a control character, `?`, or `#`. See [Path Rules](https://prometheus-proxy.com/configuration/agent/index.md#path-rules). ### pathConfig An entry in the agent's `pathConfigs` list that maps a proxy `path` to the `url` the agent fetches, its [target URL](#target-url), with a `name`, and optionally `labels`. See [Example Configs](https://prometheus-proxy.com/examples/index.md). ### Scrape Request / Response The gRPC messages exchanged over the agent's streams: the proxy sends a **ScrapeRequest** for a path, and the agent returns a **ScrapeResponse** with the fetched body, status code, and content type. ### Takeover What happens when an agent registers a path another agent already serves, without [consolidated mode](#consolidated-mode): the later registration takes the path, provided both agents present the same [identity](#agent-identity); another identity's registration is refused while the first agent is connected. The displaced agent stays connected without the path. The proxy tells it so, it logs a warning naming the agent that took the path, and its [dashboard](https://prometheus-proxy.com/agent-dashboard/index.md) shows the path `retrying`, taken over by that agent. It takes the path back once no agent serves it, as when a rolling deploy's new version stops. See [An Agent Is Connected but Serves No Paths](https://prometheus-proxy.com/troubleshooting/index.md#an-agent-is-connected-but-serves-no-paths). ### Target URL The URL an agent scrapes for a [path](#path): its [pathConfig](#pathconfig)'s `url`, or a discovered target's. A path an [embedded agent](#embedded-agent) serves from its app's registry has none, and the dashboards show its target as `in-process`. The agent reports the target URL as it registers the path, with its query's values redacted, and the proxy's dashboard shows it with any credentials redacted too. Prometheus never sees it: it scrapes the path on the proxy. ## Discovery ### Dynamic Target Discovery The agent's reconcile loop (`agent.discovery`) that keeps its registered paths in step with a watched [HOCON](#hocon) or JSON file at runtime, so targets can be added and removed without restarting the agent. It never touches the agent's [static paths](#static-and-discovered-paths). See [Dynamic Target Discovery](https://prometheus-proxy.com/configuration/agent/index.md#dynamic-target-discovery). ### Prometheus Service Discovery { #service-discovery } The proxy's HTTP endpoint that lists the registered paths as targets in Prometheus's `http_sd_config` format, so Prometheus finds them with no target in its config. It's distinct from [dynamic target discovery](#dynamic-target-discovery), the agent's side. See [Prometheus Service Discovery](https://prometheus-proxy.com/service-discovery/index.md). ### `STATIC` and `DISCOVERED` Paths A path's source, how its agent came to serve it. A `STATIC` path comes from the agent's `pathConfigs` or its code, and discovery never touches it; a `DISCOVERED` path comes from the agent's discovery file, and discovery adds, changes, and removes it. When both name the same path, the static one wins. The proxy's dashboard tags the two `cfg` and `disc`, and the agent's dashboard, its log, and its `agent_paths` metric call them `static` and `discovered`. See [Dynamic Target Discovery](https://prometheus-proxy.com/configuration/agent/index.md#dynamic-target-discovery). ## Connections ### Departed An agent that has left the proxy, by disconnecting or being [evicted](#stale-agent-cleanup), and a path no agent serves any more, since its last agent left or unregistered it. The proxy stops routing a departed path at once, so a scrape of it gets a 404, but its dashboard's Paths view keeps the path, its agent tagged [`gone`](#gone), for `proxy.dashboard.departedPathRetentionSecs` (an hour by default) or until an agent registers it again, and the status bar counts it among the departed. A path another agent still serves, as in [consolidated mode](#consolidated-mode), hasn't departed. See [Paths Whose Agent Has Gone](https://prometheus-proxy.com/web-dashboard/index.md#paths-whose-agent-has-gone). ### Heartbeat A keepalive message the agent sends after a few seconds without other traffic (5 by default), so the proxy knows the connection is still alive. See [Architecture](https://prometheus-proxy.com/architecture/index.md#heartbeat). ### Proxy Failover The agent's high-availability mechanism: an ordered `agent.proxy.endpoints` list. A failed connect, or a proxy that rejects the agent's registration, moves the agent to the next endpoint. When a connection that registered drops, the agent starts again from the head of the list, so it returns to a recovered primary at its next reconnect. One connection is active at a time. See [High Availability](https://prometheus-proxy.com/production/index.md#high-availability). ### Stale Agent Cleanup The proxy's periodic eviction of agents that have been inactive longer than [`proxy.internal.maxAgentInactivitySecs`](https://prometheus-proxy.com/configuration/proxy/index.md#internal-settings) (default 60s). An evicted agent has [departed](#departed). See [Architecture](https://prometheus-proxy.com/architecture/index.md#stale-agent-cleanup). ### Transport Filter A gRPC server filter the proxy uses to detect agent disconnects promptly. Disabling it (`transportFilterDisabled`) is required when fronting the gRPC port with an L7 proxy such as nginx. Without it, an agent is removed when its request stream ends, and the inactivity timeout covers only an agent that dies before opening its stream, or whose connection stays half-open. See [Advanced Topics](https://prometheus-proxy.com/advanced/index.md#nginx-reverse-proxy). ## Configuration and Security ### Agent Identity A named entry in the proxy's `proxy.auth` list: a token, with the path glob patterns its agents may register, which lets the proxy tell agents apart and refuse a `registerPath` outside the identity's scope. The shared [agent token](#agent-token) predates identities, and the proxy honors it as an allow-all identity. See [Per-Agent Identities](https://prometheus-proxy.com/security/index.md#per-agent-identities-and-path-authorization). ### Agent Token An optional pre-shared secret (`--agent_token` / `AGENT_TOKEN`) the agent attaches to every gRPC call so the proxy can authenticate agents at the application layer. See [Security](https://prometheus-proxy.com/security/index.md#agent-authentication-pre-shared-token). ### HOCON The format of the proxy's and the agent's config files: Human-Optimized Config Object Notation, the superset of JSON that the [Typesafe Config](https://github.com/lightbend/config) library reads. It allows comments, unquoted keys and strings, nested keys written with dots, such as `agent.proxy.hostname`, and values from environment variables, such as `${?AGENT_NAME}`. A JSON or Java properties file works too. See [HOCON Basics](https://prometheus-proxy.com/configuration/index.md#hocon-basics). ## Dashboards ### Agent Dashboard The agent's live-updating web page (`agent.dashboard`, default port `8095`) showing its connection to the proxy, each proxy endpoint's last connect error, every path with the proxy's reason for refusing one and its recent scrapes as the agent saw them, its filters, discovery, and settings, and an activity feed of what happened to them: what the proxy's dashboard can't see. A Scrape now button fetches a path's target from the agent. It's reached two ways: as a [direct agent dashboard](#direct-agent-dashboard), off by default and unauthenticated until a password is set, or as a [relayed agent dashboard](#relayed-agent-dashboard) on a proxy's [screens page](#screens-page). See [Agent Dashboard](https://prometheus-proxy.com/agent-dashboard/index.md). ### Dashboard The proxy's live-updating web page (`proxy.dashboard`, default port `8094`) showing connected agents, registered paths, [departed](#departed) ones included, and recent scrape results. Off by default, and unauthenticated until a password is set. See [Proxy Dashboard](https://prometheus-proxy.com/web-dashboard/index.md). ### Direct Agent Dashboard The [agent dashboard](#agent-dashboard) as the agent serves it, on a separate port (`agent.dashboard.enabled`), which a browser reaches directly, through `kubectl port-forward`, or as a screen the [screens page](#screens-page) lists by its URL. It answers whether or not the agent is connected, so it shows why an agent can't reach its proxy. See [Direct and Relayed Agent Dashboards](https://prometheus-proxy.com/agent-dashboard/index.md#direct-and-relayed-agent-dashboards). ### `gone` The tag the proxy dashboard's Paths view puts beside the agent of a [departed](#departed) path: the last agent that served it, which has left. The status bar counts such paths as `departed`. ### Relayed Agent Dashboard The [agent dashboard](#agent-dashboard) as a proxy shows it on its [screens page](#screens-page), through the agent's gRPC connection (`proxy.dashboard.agentScreens`, and the agent's `agent.dashboard.showOnProxy`), so the agent opens no port. Its tab is marked with a signal, and it's there only while the agent is connected to that proxy. See [Direct and Relayed Agent Dashboards](https://prometheus-proxy.com/agent-dashboard/index.md#direct-and-relayed-agent-dashboards). ### Screens Page A page the proxy serves at `/screens` on its dashboard's port while `proxy.dashboard.screens` lists any screens or `proxy.dashboard.agentScreens` is on. It shows the proxy's dashboard and each other screen, such as a [direct agent dashboard](#direct-agent-dashboard), Grafana, or Prometheus, in a separate tab, in one of three layouts: one at a time (One), two side by side (Split), or all in a grid (All). With `agentScreens` on, each connected agent that allows it gets a tab of its [relayed agent dashboard](#relayed-agent-dashboard), so the agent opens no port. See [Screens Page](https://prometheus-proxy.com/screens-page/index.md). ### View One of a dashboard's tabs, each at a separate address: the proxy dashboard's Agents, Paths, Activity, and Settings, and the agent dashboard's Paths, Connection, Activity, and Settings. The [screens page](#screens-page)'s One, Split, and All aren't views but layouts, which arrange screens. See [Proxy Dashboard](https://prometheus-proxy.com/web-dashboard/index.md#four-layouts) and [Agent Dashboard](https://prometheus-proxy.com/agent-dashboard/index.md).