JVM metrics describe heap and non-heap memory, garbage collection, threads, and other runtime activity. You can collect them in Kubernetes without rebuilding the application image by injecting a Java agent, connecting a sidecar to an existing JMX endpoint, or using a compatible eBPF-based collector. Each approach has different permissions and runtime requirements.
The blocker is ownership. Engineers who need those numbers often do not control the images running the JVMs. This post covers three ways to collect JVM metrics in Kubernetes without rebuilding a single image, and how to validate each before you turn it on.
Key Takeaways
- Start with what already exists. A supported Prometheus endpoint may avoid new instrumentation. Otherwise, choose agent injection, remote JMX, or a compatible collector.
- No rebuild does not mean no runtime change. Startup injection changes the pod configuration and requires new pods. Coordinate with the application owner.
- Verify the actual metric set. Tool, JVM version, and configuration determine which heap and GC signals you receive.
- Canary before rollout. Check startup, metric labels, scrape health, application latency, and memory overhead.
Why platform teams need JVM metrics they cannot instrument for
Monitoring JVM metrics in Kubernetes usually falls to whoever runs the cluster, not whoever wrote the service. The ownership gap is the whole problem. A platform team runs the clusters and the autoscalers. The applications are owned by product teams. Those product teams ship images with a distroless base or a JRE-only base that has jcmd missing, no shell, and no package manager at all. The image build lives in another team’s repository, under that team’s CI pipeline and review process.
Adding a metrics agent to the image means a change request into a repo you do not own, a review cycle you do not control, and a rebuild for every service. That path stalls, so metrics never get collected and rightsizing never happens.
Heap usage and container working set measure different things. Heap used is memory occupied by objects; committed heap is memory available for the JVM to use; maximum heap is its configured upper bound. Container memory also includes non-heap and native allocations. For how these signals affect requests and limits, see Java Kubernetes rightsizing.
Path 1 – inject a Java agent without touching the image
An init container can copy a Java agent JAR and configuration into an emptyDir volume. The application starts with -javaagent pointing at that volume. This preserves the application image, but changes its runtime: review compatibility and rollout with the application owner.
Month two reveals the real cost. Retention, cardinality, and alert noise land on platform teams, so scope labels before you scale the rollout.
The OpenTelemetry Operator can automate injection through an Instrumentation resource and the instrumentation.opentelemetry.io/inject-java annotation. Admission-time mutation still requires permission to change the workload and new pods. Configure the exporter and collector explicitly; an OTLP pipeline is different from a Prometheus HTTP endpoint.
Mount the agent and preserve existing JVM options
JAVA_TOOL_OPTIONS is read when the JVM is created, so it can work with launch mechanisms beyond the java command. JDK_JAVA_OPTIONS is a Java 9+ launcher facility. Confirm which variable the application actually honors, and append the agent flag without discarding existing heap, GC, or other settings. The example assumes you build an approved init image containing the pinned JAR and a reviewed exporter.yaml; replace the example image names.
# prometheus/jmx_exporter javaagent 1.7.0, init image builds from the upstream JAR
apiVersion: apps/v1
kind: Deployment
metadata:
name: checkout-api
spec:
replicas: 3
selector:
matchLabels:
app: checkout-api
template:
metadata:
labels:
app: checkout-api
spec:
initContainers:
- name: jmx-agent
# Pre-baked image: COPY the pinned JAR and exporter.yaml into /agent.
image: registry.example.com/jmx-agent:1.7.0
command: ["sh", "-c", "cp -r /agent/. /agents/"]
volumeMounts:
- name: agent
mountPath: /agents
securityContext:
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
containers:
- name: app
image: registry.example.com/checkout-api:2.14.0
env:
- name: JAVA_TOOL_OPTIONS
value: "-javaagent:/agents/jmx_prometheus_javaagent-1.7.0.jar=9404:/agents/exporter.yaml"
ports:
- name: jmx-metrics
containerPort: 9404
volumeMounts:
- name: agent
mountPath: /agents
securityContext:
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
volumes:
- name: agent
emptyDir:
sizeLimit: 32Mi
The JMX Exporter Java agent uses -javaagent; it is not a native JVMTI agent. The metrics endpoint in this example binds to all interfaces on port 9404. Restrict network access to authorized scrapers. The writable emptyDir is separate from the read-only application root filesystem.
A ServiceMonitor selects Service labels, and its endpoint refers to a named Service port. Create both resources, and ensure the Prometheus Operator deployment selects this ServiceMonitor and namespace:
apiVersion: v1
kind: Service
metadata:
name: checkout-api-jvm
labels:
app: checkout-api
spec:
selector:
app: checkout-api
ports:
- name: jmx-metrics
port: 9404
targetPort: jmx-metrics
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: checkout-api-jvm
spec:
selector:
matchLabels:
app: checkout-api
endpoints:
- port: jmx-metrics
path: /metricsUse a PodMonitor instead when there is no Service, which is common for jobs and DaemonSets. The convention is port 9404 for jmx_exporter. Cast AI uses 29404 and up for its own injection, so keep the two conventions separate.
How to verify compatibility before enabling injection
Record startup time, request latency, CPU, memory, and error rate before changing one canary replica. Verify the chosen agent release supports the JVM vendor and version. Startup injection does not require jcmd or dynamic attach, which matters for distroless and JRE-only images.
After the canary starts, inspect the metrics endpoint from an authorized diagnostic environment, check the expected metric families, and confirm the scrape target is UP. Compare application behavior with the baseline before widening the rollout. Metric names depend on exporter rules; a successful HTTP response alone is insufficient.
Check for an existing APM or metrics agent before injection. Multiple agents can interact, change overhead, or emit overlapping telemetry. Pin versions and keep a rollback that removes the injection settings and recreates the affected pods.
When security policy blocks it
Startup Java-agent injection does not inherently require host-level privileges or ptrace. It can still be blocked by admission policies, image allow-lists, filesystem permissions, or restrictions on pod mutation. Dynamic attach and node-level collectors have separate requirements.
If Spring Boot Actuator or another exporter already exposes a Prometheus endpoint, configure an authorized scraper for it. The prometheus.io/* annotations are a convention, not an automatic Kubernetes scraping feature: the collector must be configured to honor them.
How Cast AI collects JVM metrics
Cast AI Workload Autoscaler supports auto-instrumentation, scraping an existing metrics endpoint, and using metrics from your Prometheus setup. Auto-instrumentation adds an init container and startup Java-agent flag at pod admission; existing pods need recreation. It supports Java 9+, while existing-endpoint and Prometheus approaches can support Java 8. The injection label is workloads.cast.ai/jmx-exporter-injected. Confirm prerequisites and supported metric names in the JVM optimization documentation.

Path 2 – the JMX exporter sidecar
Standalone JMX Exporter runs outside the application JVM and connects to its remote JMX endpoint. It suits applications that already expose securely configured JMX. Adding a sidecar alone does not enable JMX inside the application.
# Inside an approved sidecar image containing the pinned standalone JAR:
java -jar jmx_prometheus_standalone-1.7.0.jar 9404 /config/exporter.yamlMount a reviewed exporter configuration and required credentials from a Kubernetes Secret. Configure the target JVM with authenticated, TLS-protected remote JMX, predictable registry/RMI ports, and an advertised hostname reachable by the sidecar. Do not expose an unauthenticated JMX management endpoint just to obtain metrics.
Containers in one pod share networking, so an appropriately configured local JMX endpoint can be reached through loopback. For cross-pod access, account for RMI address advertisement and both the registry and connector ports. A NetworkPolicy does not replace JMX authentication.
Remote JMX adds operational complexity. The JMX Exporter project recommends Java-agent mode when possible because it avoids configuring a remote JMX connection.
Path 3: eBPF-based JVM observation
An eBPF-based collector can collect some runtime signals without rebuilding application images, but capabilities are tool-specific. Do not assume that every metric comes exclusively from outside the JVM. For example, Grafana Beyla uses HotSpot USDT probes for JVM memory-pool metrics and a Java agent for other runtime metrics, including thread and GC-duration signals.
Before selecting this route, verify the collectorโs JVM compatibility, kernel requirements, enabled metric features, and security permissions. Node-level deployment can require access unavailable under restrictive cluster policies.
Validate that the collector supplies the signals your rightsizing workflow consumes. A service-latency view is not automatically a heap-sizing view, and โzero codeโ does not guarantee zero application instrumentation or zero overhead.
Which path fits: the trade-offs
| Approach | Required access | Main trade-off |
|---|---|---|
| Java-agent injection | Pod mutation, approved agent image, new pods | Direct JVM metrics; test in-process overhead and agent interactions. |
| OpenTelemetry injection | Operator configuration, workload annotation, exporter pipeline | Runtime telemetry plus other instrumentation; configure only what you need. |
| JMX sidecar | Sidecar deployment and securely enabled remote JMX | Preserves app image; adds JMX/RMI configuration and another process. |
| eBPF-based collector | Collector-specific node permissions and JVM support | Coverage varies; some JVM signals may still use an agent. |
| Existing endpoint | Authorized scrape access and compatible metrics | Avoids new instrumentation when required signals already exist. |
One last constraint matters at fleet scale. Agent versions drift, so pin the JAR digest in the init container image and treat an upgrade as a deliberate rollout, never a floating tag.
What rightsizing actually needs from these metrics
Collect heap used, committed, and maximum; non-heap memory; GC activity and pause duration; and thread counts. Compare these with container memory and workload demand over a representative period. Prometheus and OpenTelemetry naming differs, and JMX Exporter output depends on its configuration. Map actual metric families before building alerts or sizing rules.
In Cast AI, the JVM filter identifies detected Java workloads. A JVM badge alone does not confirm that metrics are flowing: open the workload and verify heap metrics and the selected data source.

The signal that separates a good limit from a bad one
A gap between used and committed heap is a useful clue, not proof of waste. Keep room for demand spikes, GC behavior, native allocations, and the applicationโs latency target. Neither peak heap used nor container working set alone defines a safe container limit.
For the next step, compare heap configuration, container limits, and requests using the JVM rightsizing workflow. Change one setting at a time and validate under representative traffic.
If two pipelines report the same JVM, keep source labels or deduplication rules so dashboards do not sum overlapping observations. Collecting both does not inherently double-count; incorrect aggregation does.
Conclusion
Choose the collection path that fits your workload ownership and security policies. Validate metrics and application behavior on a canary, then expand deliberately. Once heap and container signals are trustworthy, use them to guide JVM-aware rightsizing.
Frequently asked questions
Yes. Startup agent injection can mount a JAR from an init container, or a sidecar can connect to existing remote JMX. Compatible collectors and existing Prometheus endpoints provide other options. Runtime configuration and permissions still matter.
No. An agent runs inside the JVM and can affect resource consumption or interact with other agents. Check supported versions, preserve existing JVM options, and compare a canary with a baseline.
No. Startup injection uses the -javaagent option when the JVM starts. jcmd is a separate diagnostic tool and is not a prerequisite for this collection path.
Yes, through supported existing metrics endpoints or Prometheus integration. Cast AI auto-instrumentation requires Java 9 or later; choose the collection method that matches your runtime.



