# 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.

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 }
outside the firewallPrometheus ─:8080─▶ proxy ◀─:50051─
inside the firewall─ agent ─▶ app :9100
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, 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.