Prometheus exporter for monitoring Xray-core tunnels.
Features:
- Multiple tunnel support in a single instance
- Current VLESS URLs: RAW/TCP, XHTTP, gRPC, WebSocket, HTTPUpgrade, and mKCP
- Native Xray JSON config (
xray_config_file) for protocols and transports registered by the pinned Xray-core - Subscriptions: VLESS, VMess, Trojan, Shadowsocks links, native Xray JSON, and supported Clash proxy lists
- HTTP, public-IP, and download health checks with TTFB latency
- YAML configuration with hot reload
- Automatic SOCKS port allocation
- Per-tunnel settings
- Optional Pushgateway delivery, Kubernetes leader election, and one-shot execution
Documentation on
maindescribes the current source. For an installed binary or Docker image, use the README at its release tag; new features may not yet be inlatest. The Helm chart updates its application version separately.
Download a pre-built binary:
# Linux amd64
wget https://github.com/batonogov/xray-health-exporter/releases/latest/download/xray-health-exporter-linux-amd64
chmod +x xray-health-exporter-linux-amd64
# Linux arm64
wget https://github.com/batonogov/xray-health-exporter/releases/latest/download/xray-health-exporter-linux-arm64
chmod +x xray-health-exporter-linux-arm64
# Linux arm (32-bit)
wget https://github.com/batonogov/xray-health-exporter/releases/latest/download/xray-health-exporter-linux-arm
chmod +x xray-health-exporter-linux-armDocker:
# Pull latest
docker pull ghcr.io/batonogov/xray-health-exporter:latestThe Docker image runs as an unprivileged user
xray(UID 10001)
Helm (Kubernetes):
helm repo add batonogov https://batonogov.github.io/helm-charts
helm install xray-health-exporter batonogov/xray-health-exporter -f values.yamlSee charts/xray-health-exporter — the chart includes leader election, RBAC for Lease, and an optional ServiceMonitor.
- Create a configuration file
config.yaml:
defaults:
check_url: "https://www.google.com"
check_interval: "30s"
check_timeout: "30s"
# Subscriptions (optional) — automatic server fetching
subscriptions:
- url: "https://provider.example.com/api/v1/client/subscribe?token=xxx"
update_interval: "1h"
tunnels:
# Option 1: VLESS URL
- name: "Server 1"
url: "vless://uuid@host1:443?type=tcp&security=reality&pbk=...&sni=google.com"
# Option 2: native Xray JSON config
- name: "Server 2"
xray_config_file: "/etc/xray/server2.json"See config.example.yaml for a full example.
- Run:
# Docker
docker run --rm \
-v $(pwd)/config.yaml:/app/config.yaml:ro \
-p 9273:9273 \
ghcr.io/batonogov/xray-health-exporter:latest
# Downloaded binary
CONFIG_FILE=./config.yaml ./xray-health-exporter-linux-amd64
# From source (requires Go 1.27+)
CONFIG_FILE=./config.yaml go run ./cmd/exporterAll xray_tunnel_* metrics contain labels name, server, security, and sni. Key metrics:
xray_tunnel_up{name, server, security, sni}- tunnel status (1=up, 0=down)xray_tunnel_latency_seconds{name, server, security, sni}- TTFB (time to first byte) latencyxray_tunnel_latency_histogram_seconds{name, server, security, sni}- TTFB histogramxray_tunnel_check_total{name, server, security, sni, result}- check counterxray_tunnel_last_success_timestamp{name, server, security, sni}- timestamp of the last successful checkxray_tunnel_http_status{name, server, security, sni}- HTTP status code from the checkxray_tunnel_error_total{name, server, security, sni, reason}- categorized error counterxray_exporter_leader- 1 if this instance is actively probing tunnels (leader or leader election is disabled), 0 otherwise
See docs/metrics.md for the authoritative metric list, types, labels, buckets, and error reasons.
Example metrics:
xray_tunnel_up{name="Server 1",server="example.com:443",security="reality",sni="google.com"} 1
xray_tunnel_latency_seconds{name="Server 1",server="example.com:443",security="reality",sni="google.com"} 0.345
xray_tunnel_check_total{name="Server 1",server="example.com:443",security="reality",sni="google.com",result="success"} 42
xray_tunnel_last_success_timestamp{name="Server 1",server="example.com:443",security="reality",sni="google.com"} 1704117344
xray_tunnel_http_status{name="Server 1",server="example.com:443",security="reality",sni="google.com"} 200
The
namelabel uses the configured name, subscription metadata, or a generated fallback; see the naming rules under Configuration. Labels identify individual tunnels.
Endpoints:
/metrics- Prometheus metrics/health- HTTP-server liveness: returns200while the server is running; does not check tunnel/subscription readiness and never requires Basic Auth
When using xray_config_file in Docker, mount the JSON file separately at its configured path. Remove unused demo tunnels and subscriptions: a failed initial subscription fetch prevents startup.
Configuration is specified via a YAML file. Example:
# Global defaults (optional)
defaults:
check_url: "https://www.google.com"
check_interval: "30s"
check_timeout: "30s"
# Subscriptions — automatic server fetching (optional)
subscriptions:
- url: "https://provider.example.com/subscribe?token=xxx"
update_interval: "1h" # how often to update (default: 1h)
# List of tunnels to monitor
tunnels:
# Option 1: VLESS URL
- url: "vless://uuid@host:443?type=tcp&security=reality&pbk=...&sni=google.com"
# Current VLESS + XHTTP + Reality
- url: "vless://uuid@host:443?type=xhttp&security=reality&pbk=...&sni=example.com&fp=chrome&path=%2Fapi&mode=stream-up&extra=%7B%7D"
# Option 2: native Xray JSON config
- name: "VMess Server"
xray_config_file: "/etc/xray/vmess.json"
# With overridden parameters
- name: "Backup Server"
url: "vless://uuid@host:443?..."
check_url: "https://1.1.1.1"
check_interval: "60s"
check_timeout: "45s"
# With a custom SOCKS port (optional, auto-assigned by default)
- name: "Server 3"
url: "vless://uuid@host:443?..."
socks_port: 2080Tunnel parameters:
name(optional) - tunnel name for logs and metrics. Static tunnels use the server endpoint, ortunnel-port-Nif unavailable; subscriptions use response metadata or generated namesurl- VLESS, VMess, Trojan, or Shadowsocks URL (mutually exclusive withxray_config_file)xray_config_file- path to a native Xray JSON config (mutually exclusive withurl). The exporter replaces itslogandinboundssections with exporter-controlled settings; other top-level sections, includingoutbounds, are preservedcheck_url(optional) - URL for availability checkscheck_interval(optional) - interval between checkscheck_timeout(optional) - check timeoutmax_backoff(optional) - maximum interval after repeated failures (default:5m)backoff_multiplier(optional) - failure-backoff growth factor, at least1.0(default:2.0)check_method(optional) - health-check method:http(default),ip, ordownload(see below)ip_check_url(optional) - IP-echo URL for theipmethod (default:https://api.ipify.org?format=text)download_url(optional) - file URL for thedownloadmethod (default:https://proof.ovh.net/files/1Mb.dat)download_timeout(optional) - timeout for thedownloadmethod (default:60s)download_min_size(optional) - minimum bytes to receive for thedownloadmethod (default:51200)socks_port(optional) - custom SOCKS5 port for this tunnel. Must be in range 1-65535. Duplicate ports across tunnels are not allowed. If not specified, ports are auto-assigned starting from 1080
Subscription parameters:
url(required) - HTTP(S) URL returning text/Base64 links, native Xray JSON, or a supported Clash proxy listname(optional) - stable source name used in subscription metricsupdate_interval(optional) - positive refresh interval per source (default:1h)timeout(optional) - positive request timeout (default:30s)format(optional) -auto(default),text,xray, orclashheaders/user_agent(optional) - custom request headers and User-Agent
VLESS URLs follow the current Xray share-link format. Supported transports are tcp/raw, xhttp/splithttp, grpc, ws/websocket, httpupgrade, and kcp/mkcp. Legacy type=http, h2, and h3 are converted to XHTTP stream-one. Supported parameters include encryption, flow, XHTTP host/path/mode/extra, gRPC serviceName/authority/mode/multiMode, WebSocket and HTTPUpgrade host/path, mKCP mtu/tti, fm (FinalMask), TLS sni/fp/alpn/ech/pcs/vcn, and REALITY pbk/sid/pqv/spx. See docs/configuration.md for validation rules and defaults.
Notes:
- At least one tunnel or subscription must be specified
- Subscription lists support
vless://,vmess://,trojan://, andss://; unsupported formats/options fail explicitly - Upgrade note: an unsupported entry rejects the entire subscription response; unknown protocols are no longer silently skipped
- VMess supports
auto,aes-128-gcm, andchacha20-poly1305;none,zero, and KCP seeds are rejected. Subscription redirects never sendReferer - Sources refresh independently; new subscriptions and interval changes apply without a restart. Failed refreshes retain the last working list in memory; unchanged tunnels keep running
- Empty or invalid responses never remove servers. Remove a subscription from YAML to remove its servers. RUN_ONCE fails on any subscription error
xray_subscription_*metrics expose refresh health, last success, server count, and errors; see configuration and metrics. Applying a saved response preserves newer fetch failures and the original fetch timestamp.- SOCKS ports are assigned automatically starting from 1080 (1080, 1081, 1082...), or can be set explicitly per tunnel via
socks_port - Duration format: "30s", "1m", "1h30m" — intervals, timeouts, and max_backoff must be positive; invalid values reject startup/reload
- Configuration priority is per-tunnel YAML, then YAML
defaults, supported environment defaults, and finally built-in defaults
Three health-check methods are available, configurable per tunnel via check_method (or globally via defaults.check_method):
http(default) - GET thecheck_url; status200,301,302, or307passes.ip- GET an IP-echo service through the proxy with status200, then compare its response text with the direct host response. The current implementation compares strings without validating IP syntax: use a plain-text IP service. This is a heuristic; a working proxy can share the host's public IP.download- Require status200, then download at leastdownload_min_sizebytes through the proxy withindownload_timeout.
All three methods measure successful-check latency as TTFB (time to first byte). See docs/check-methods.md for exact pass/fail behavior.
defaults:
check_method: "ip"
ip_check_url: "https://api.ipify.org?format=text"
tunnels:
- name: "Server 1"
url: "vless://..."
check_method: "download"
download_url: "https://proof.ovh.net/files/1Mb.dat"
download_min_size: 51200| Variable | Default | Description |
|---|---|---|
CONFIG_FILE |
/app/config.yaml |
Path to YAML configuration |
LISTEN_ADDR |
:9273 |
HTTP server address |
LOG_FORMAT |
text |
Log format: text or json |
LOG_LEVEL |
info |
Log level: debug, info, warn/warning, error |
XRAY_LOG_LEVEL |
warning |
Xray log level |
DEBUG |
false |
(Deprecated) Verbose output, use LOG_LEVEL=debug instead |
LEADER_ELECTION |
false |
Enable k8s leader election (see below) |
LEADER_ELECTION_NAMESPACE |
pod namespace | Namespace for the Lease object |
LEADER_ELECTION_NAME |
xray-health-exporter |
Lease name |
LEADER_ELECTION_IDENTITY |
$HOSTNAME |
Unique replica ID |
CHECK_METHOD |
http |
Default check method if not set in YAML: http, ip, or download |
IP_CHECK_URL |
https://api.ipify.org?format=text |
IP-echo URL for the ip method |
DOWNLOAD_URL |
https://proof.ovh.net/files/1Mb.dat |
File URL for the download method |
DOWNLOAD_TIMEOUT |
60s |
Timeout for the download method |
DOWNLOAD_MIN_SIZE |
51200 |
Minimum bytes for the download method |
RUN_ONCE |
false |
If true, run one check cycle, print metrics to stdout, and exit (see below) |
METRICS_PROTECTED |
false |
Enable Basic Auth on /metrics; /health stays open |
METRICS_USERNAME |
metricsUser |
Basic Auth username for /metrics |
METRICS_PASSWORD |
(required when protected) | Basic Auth password for /metrics |
METRICS_PUSH_URL |
(empty) | Full Pushgateway URL; may include user:pass@. Empty disables push |
METRICS_PUSH_INTERVAL |
min static-tunnel check_interval, or 30s |
Set at startup; subscription tunnels are excluded |
METRICS_INSTANCE |
os.Hostname() |
Value of the instance grouping label for pushed metrics |
Set RUN_ONCE=true to execute a single check cycle and exit — useful for CI pipelines, scripts, and debugging. In this mode the exporter:
- Loads the config and resolves subscriptions.
- Starts Xray instances for all tunnels.
- Performs exactly one health-check per tunnel (concurrently).
- Prints all metrics to stdout in Prometheus text-exposition format.
- Stops all tunnels and exits.
Exit code: 0 if all tunnels are up, 1 if any tunnel is down or an error occurred.
RUN_ONCE=true CONFIG_FILE=./config.yaml go run ./cmd/exporterLoading or initialization failures exit RUN_ONCE before metrics are printed. Subscription status metrics (xray_subscription_*) are populated only in daemon mode.
Note: In run-once mode the HTTP server, config watcher, and subscription watcher are not started. Leader election is ignored — the check always runs locally.
When the exporter runs behind NAT or in a network where Prometheus cannot scrape /metrics, you can push metrics to a Pushgateway instead:
METRICS_PUSH_URL=https://user:[email protected]:9091
METRICS_PUSH_INTERVAL=30s
METRICS_INSTANCE=node-1- Push is complementary — the
/metricsHTTP endpoint stays available. - Push only happens when this instance is the leader (or leader election is disabled).
- Credentials embedded in the URL (
user:pass@) are extracted for HTTP Basic Auth automatically. - The URL path is ignored —
prometheus/pushbuilds/metrics/job/xray-health-exporteritself, so do not include a reverse-proxy path prefix inMETRICS_PUSH_URL. - The full default registry is pushed (including
go_*andprocess_*metrics), not onlyxray_tunnel_*series.
Ready-made Helm chart:
batonogov/xray-health-exporter— deploys the exporter with everything below out of the box (replicas, leader election, RBAC for Lease, optionalServiceMonitor/PrometheusRule).helm repo add batonogov https://batonogov.github.io/helm-charts helm install xray-health-exporter batonogov/xray-health-exporter \ -f values.yaml
When running with replicas: >1 and scraping via ServiceMonitor, Prometheus will hit each pod independently, duplicating tunnel metrics. To solve this, enable leader election:
env:
- name: LEADER_ELECTION
value: "true"
- name: LEADER_ELECTION_IDENTITY
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: LEADER_ELECTION_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespaceBehavior:
- Only the leader initializes Xray tunnels and publishes
xray_tunnel_*metrics;xray_exporter_leader=1. - Followers respond to
/metricsand/health, publishxray_exporter_leader=0, and retain general process/exporter metrics. The former leader'sxray_tunnel_*series are cleared after its checks stop. - On graceful leader termination (SIGTERM), the Lease is released immediately (
ReleaseOnCancel), and a follower takes over within ~RetryPeriod(~5s). On a hard crash — withinLeaseDuration(~30s).
Warning: If multiple different exporter deployments run in the same namespace, you must set a unique LEADER_ELECTION_NAME for each — otherwise they will contend for the same Lease.
Warning: LEADER_ELECTION=true requires running inside a Kubernetes pod (InClusterConfig is used). Outside a cluster, the exporter will fail with a config loading error.
Minimal RBAC (creates and updates Lease):
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: xray-health-exporter
rules:
- apiGroups: ["coordination.k8s.io"]
resources: ["leases"]
verbs: ["get", "create", "update"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: xray-health-exporter
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: xray-health-exporter
subjects:
- kind: ServiceAccount
name: xray-health-exporterSince followers do not publish any xray_tunnel_* metrics, standard alerts (xray_tunnel_up == 0, xray_tunnel_latency_seconds > X) fire only on leader data — duplicates are excluded without additional PromQL filters.
Add to prometheus.yml:
scrape_configs:
- job_name: 'xray-health'
static_configs:
- targets: ['localhost:9273']Alert examples:
groups:
- name: xray
rules:
# Tunnel is down
- alert: XrayTunnelDown
expr: xray_tunnel_up == 0
for: 5m
labels:
severity: critical
annotations:
summary: "Tunnel {{ $labels.name }} is down"
description: "Tunnel {{ $labels.name }} ({{ $labels.server }}, {{ $labels.security }}) has been down for more than 5 minutes"
# High latency
- alert: XrayHighLatency
expr: xray_tunnel_latency_seconds > 2
for: 10m
labels:
severity: warning
annotations:
summary: "High latency on {{ $labels.name }}"
description: "Tunnel {{ $labels.name }} has latency of {{ $value }}s (threshold: 2s)"
# Tunnel not checked recently
- alert: XrayNoRecentCheck
expr: (time() - xray_tunnel_last_success_timestamp) > 300
for: 5m
labels:
severity: warning
annotations:
summary: "{{ $labels.name }} has not been checked recently"
description: "Tunnel {{ $labels.name }} has not been successfully checked for {{ $value }}s"A ready-to-use Grafana dashboard is available in the grafana/dashboard.json file.
Panels:
- Overview — total tunnels, UP/DOWN counts, health rate, average latency
- Tunnel Status — table with current status, latency, last success time, and HTTP status code per tunnel
- Latency — time series of connection latency per tunnel
- Check Results — success/failure check rate per tunnel
- HTTP Status Codes — HTTP response code distribution over time
- Last Success — time since last successful health check per tunnel
Import:
- Open Grafana → Dashboards → Import
- Upload
grafana/dashboard.jsonor paste its contents - Select your Prometheus data source
- Click Import
# Install pre-commit hooks
task install-hooks
# Run tests
task test
# or
go test -v -cover ./...
# Run tests with coverage report
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
# Local build
task buildAutomated testing in Pull Requests:
- All tests run on every PR
- Code coverage check (minimum 75%)
- Code formatting check
- Build check
- Automatic comment with results in PR
Pre-commit checks:
- Go formatting (
go fmt) - Run tests
- Build check
- Secret protection (gitleaks, detect-private-key)
MIT