An AI app can look healthy and still be failing. The container is up, the health check passes, and yet users wait twelve seconds for the first word because the GPU is full or the model server is queueing requests. Standard uptime monitoring does not catch that.
This guide shows how to monitor Dockerized AI applications with Prometheus and Grafana, from the container and GPU layer up to AI-specific numbers like time to first token and tokens per minute. You get a working Docker Compose stack, the PromQL queries worth putting on a dashboard, alert rules, and fixes for the problems that trip people up.
Table of Content
- What Should You Monitor in Dockerized AI Applications?
- How Prometheus and Grafana Work Together
- Monitoring Dockerized AI Applications via Prometheus and Grafana
- Common Prometheus and Grafana Monitoring Problems
- Security and Performance Best Practices for AI Monitoring
- Frequently Asked Questions
What Should You Monitor in Dockerized AI Applications?
AI services fail in ways ordinary web apps do not. Watch four layers:
Layer | What to track | Tool that provides it |
|---|---|---|
Host | CPU, RAM, disk, network | node_exporter |
Containers | CPU, memory, restarts, OOM kills | cAdvisor |
GPU | Utilization, VRAM used, temperature, power | NVIDIA DCGM exporter |
AI application | Request latency, time to first token, error rate, tokens used, requests in progress | Your own metrics via prometheus_client |
The fourth layer is the one most guides skip, and it is the one that tells you whether users are happy. A GPU at 95 percent utilization is fine if latency is steady. A GPU at 30 percent with rising latency points to a queue or a bottleneck elsewhere.
See our guide on monitoring resource usage for self-hosted AI applications.
How Prometheus and Grafana Work Together
Prometheus pulls metrics from each target on a schedule. Grafana reads from Prometheus and draws the charts. Nothing needs to push data anywhere.
AI app (/metrics) ----+
cAdvisor (:8080) -----+
node_exporter (:9100) -+--> Prometheus (scrapes every 15s) --> Grafana (dashboards)
DCGM exporter (:9400) -+ |
+--> alert rules
Monitoring Dockerized AI Applications via Prometheus and Grafana
Run Prometheus, Grafana, cAdvisor, and node_exporter in Docker Compose. Add the NVIDIA DCGM exporter if you use a GPU. Expose a /metrics endpoint from your app with the prometheus_client library, and track request latency, time to first token, error rate, and token usage. Build Grafana panels from those metrics, then add alerts for errors, slow responses, memory pressure, and cost spikes.
Step 1: Add metrics to your AI app
This example uses a FastAPI chatbot, like the one in our guide on building a production-ready AI chatbot with Python, FastAPI, and the OpenAI API. The same idea works with any Python service.
pip install prometheus-client

Now, create a metrics Python file and add a script in it. See our walkthrough on deploying an AI API with Python and Nginx on Ubuntu.
# metrics.py
from prometheus_client import Counter, Gauge, Histogram
REQUESTS = Counter("chat_requests_total", "Chat requests", ["status"])
LATENCY = Histogram(
"chat_request_duration_seconds", "Total request time",
buckets=(0.5, 1, 2, 5, 10, 20, 30, 60),
)
TTFT = Histogram(
"chat_time_to_first_token_seconds", "Time until the first token",
buckets=(0.1, 0.25, 0.5, 1, 2, 5, 10),
)
TOKENS = Counter("llm_tokens_total", "Tokens used", ["model", "direction"])
IN_FLIGHT = Gauge(
"chat_in_flight_requests", "Streams in progress", multiprocess_mode="livesum"
)
Record them inside your streaming handler:
import time
from metrics import REQUESTS, LATENCY, TTFT, TOKENS, IN_FLIGHT
start = time.perf_counter()
first = True
IN_FLIGHT.inc()
try:
async for event in stream:
if event.type == "response.output_text.delta" and first:
TTFT.observe(time.perf_counter() - start)
first = False
# ...yield the delta to the client as before
REQUESTS.labels(status="ok").inc()
except Exception:
REQUESTS.labels(status="error").inc()
raise
finally:
LATENCY.observe(time.perf_counter() - start)
IN_FLIGHT.dec()
# when the final usage object arrives:
TOKENS.labels(model=settings.openai_model, direction="input").inc(u.input_tokens)
TOKENS.labels(model=settings.openai_model, direction="output").inc(u.output_tokens)
Two details save you pain later:
- Custom histogram buckets. The default buckets stop at 10 seconds, which is too short for LLM answers. The buckets above fit streamed chat responses. Adjust them to your own latency range.
- Keep labels small. Use labels such as status and model. Never use user IDs, session IDs, or prompt text as labels. Every unique value creates a new time series, and that can overload Prometheus.
Handle several workers correctly
If you run Uvicorn or Gunicorn with more than one worker, each worker keeps its own counters, and a scrape returns whichever worker answered. The numbers jump around. Use the multiprocess mode of prometheus_client:
from fastapi import Response
from prometheus_client import CONTENT_TYPE_LATEST, CollectorRegistry, generate_latest, multiprocess
@app.get("/metrics")
def metrics():
registry = CollectorRegistry()
multiprocess.MultiProcessCollector(registry)
return Response(generate_latest(registry), media_type=CONTENT_TYPE_LATEST)
Set PROMETHEUS_MULTIPROC_DIR=/tmp/prom in the container, and make sure the folder exists, is writable, and is empty on startup. A tmpfs mount handles that. Gauges need a multiprocess_mode, as shown above.
If your model server is not Python, check what it already exposes. vLLM provides a Prometheus /metrics endpoint, and llama.cpp’s server has a –metrics option. In the Ollama versions I used, there was no native Prometheus endpoint, so I measured it from the calling application instead.
Step 2: Write the Docker Compose stack
Make sure Docker and Docker Compose are installed on your Ubuntu server (and review our best practices for securing Docker configurations for Linux applications) before creating your Compose file:
services:
app:
build: .
environment:
PROMETHEUS_MULTIPROC_DIR: /tmp/prom
tmpfs:
- /tmp/prom
ports:
- "127.0.0.1:8000:8000"
prometheus:
image: prom/prometheus:v3.0.0 # pin a current release
command:
- --config.file=/etc/prometheus/prometheus.yml
- --storage.tsdb.retention.time=15d
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
- ./alerts.yml:/etc/prometheus/alerts.yml:ro
- prom-data:/prometheus
ports:
- "127.0.0.1:9090:9090"
grafana:
image: grafana/grafana:11.3.0 # pin a current release
environment:
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin
secrets:
- grafana_admin
volumes:
- grafana-data:/var/lib/grafana
ports:
- "127.0.0.1:3000:3000"
cadvisor:
image: gcr.io/cadvisor/cadvisor:v0.49.1 # pin a current release
command:
- --docker_only=true
- --housekeeping_interval=15s
volumes:
- /:/rootfs:ro
- /var/run:/var/run:ro
- /sys:/sys:ro
- /var/lib/docker/:/var/lib/docker:ro
devices:
- /dev/kmsg
node-exporter:
image: prom/node-exporter:v1.8.2 # pin a current release
command:
- --path.rootfs=/host
pid: host
volumes:
- /:/host:ro,rslave
dcgm-exporter: # remove this service if you have no NVIDIA GPU
image: nvcr.io/nvidia/k8s/dcgm-exporter:<tag> # use the current tag from NVIDIA NGC
cap_add:
- SYS_ADMIN
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
volumes:
prom-data:
grafana-data:
secrets:
grafana_admin:
file: ./secrets/grafana_admin.txt
Notice that every published port is bound to 127.0.0.1. Prometheus and Grafana have no business being open to the internet, and Docker’s port publishing can bypass ufw rules. Reach them through an SSH tunnel, a VPN, or an authenticated reverse proxy.
Reach them through an SSH tunnel, a VPN, or an authenticated reverse proxy. Our guide on how to secure a publicly accessible AI web interface on Linux covers the proxy setup.
Step 3: Configure Prometheus to scrape everything
Targets use Compose service names, not localhost. Inside a container, localhost means that container itself, which is the most common reason a target shows as down.
# prometheus.yml
global:
scrape_interval: 15s
rule_files:
- /etc/prometheus/alerts.yml
scrape_configs:
- job_name: app
static_configs:
- targets: ["app:8000"]
- job_name: cadvisor
static_configs:
- targets: ["cadvisor:8080"]
- job_name: node
static_configs:
- targets: ["node-exporter:9100"]
- job_name: gpu
static_configs:
- targets: ["dcgm-exporter:9400"]
Start everything with docker compose up -d, then open http://localhost:9090/targets in your SSH connection and port-forwarding tunnel. All four jobs should read UP.
Step 4: Connect Grafana and import dashboards
Open Grafana, go to Connections, add a Prometheus data source, and set the URL to http://prometheus:9090. For a repeatable setup, provision the data source with a YAML file in /etc/grafana/provisioning/datasources/ so a rebuilt container needs no clicks.
Import community dashboards to get started fast. Node Exporter Full (ID 1860) and the NVIDIA DCGM Exporter dashboard (ID 12239) are widely used. Search the Grafana dashboard library for a current cAdvisor container dashboard. Check each one against your label names, because dashboards written for older setups sometimes expect different labels.
Step 5: Build the AI panels that matter
These queries go into new panels. Put them at the top of your main dashboard.
p95 request latency
histogram_quantile(0.95, sum by (le) (rate(chat_request_duration_seconds_bucket[5m]))) |
|---|
p95 time to first token
histogram_quantile(0.95, sum by (le) (rate(chat_time_to_first_token_seconds_bucket[5m]))) |
|---|
Error rate
sum(rate(chat_requests_total{status=”error”}[5m])) / sum(rate(chat_requests_total[5m])) |
|---|
Tokens per minute by model and direction
sum by (model, direction) (rate(llm_tokens_total[1m])) * 60 |
|---|
Requests in progress
sum(chat_in_flight_requests) |
|---|
CPU per container
sum by (name) (rate(container_cpu_usage_seconds_total{name!=””}[5m])) |
|---|
Memory per container
container_memory_working_set_bytes{name!=””} |
|---|
GPU memory used (percent)
DCGM_FI_DEV_FB_USED / (DCGM_FI_DEV_FB_USED + DCGM_FI_DEV_FB_FREE) * 100 |
|---|
Pair them on one row: GPU utilization next to p95 time to first token next to requests in progress. When latency rises while in-flight requests climb, you have a capacity problem. When latency rises and in-flight stays flat, look at the model, the network, or the upstream API.
Step 6: Add alerts that matter
Alerts should wake you for user-facing problems, not every small spike. Start with these rules:
# alerts.yml
groups:
- name: ai-app
rules:
- alert: HighErrorRate
expr: sum(rate(chat_requests_total{status="error"}[5m])) / sum(rate(chat_requests_total[5m])) > 0.05
for: 5m
labels: { severity: page }
annotations:
summary: "More than 5% of chat requests are failing"
- alert: SlowFirstToken
expr: histogram_quantile(0.95, sum by (le) (rate(chat_time_to_first_token_seconds_bucket[5m]))) > 3
for: 10m
labels: { severity: warn }
annotations:
summary: "p95 time to first token is over 3 seconds"
- alert: ContainerOOMKilled
expr: increase(container_oom_events_total[15m]) > 0
labels: { severity: page }
annotations:
summary: "A container was killed for running out of memory"
- alert: GPUMemoryHigh
expr: DCGM_FI_DEV_FB_USED / (DCGM_FI_DEV_FB_USED + DCGM_FI_DEV_FB_FREE) > 0.95
for: 10m
labels: { severity: warn }
annotations:
summary: "GPU memory is above 95% for 10 minutes"
- alert: TokenSpendSpike
expr: sum(increase(llm_tokens_total[1h])) > 2000000
labels: { severity: warn }
annotations:
summary: "More than 2M tokens used in the last hour"
The token threshold is a placeholder. Set it to about twice your normal hourly use. The last rule has caught more real incidents for me than any CPU alert, because a leaked key (follow our checklist on securing AI API keys on a Linux server) or a buggy retry loop shows up as a token jump first.
Prometheus evaluates these rules, and Alertmanager sends the notifications to email, Slack, or PagerDuty. If you would rather skip Alertmanager, you can recreate the same queries as Grafana alert rules and use Grafana’s contact points.
Common Prometheus and Grafana Monitoring Problems
Problem | Likely cause | Fix |
|---|---|---|
Target shows DOWN | Using localhost inside Compose, or wrong port | Use the service name and container port |
Counters jump up and down | Several app workers without multiprocess mode | Set PROMETHEUS_MULTIPROC_DIR and use MultiProcessCollector |
Container name label is empty | cgroup v2 or containerd setups | Filter with id or the Compose label container_label_com_docker_compose_service |
cAdvisor uses a lot of CPU | Too many metrics, short housekeeping interval | Add –docker_only=true, raise the interval, drop unused metrics |
No GPU metrics | Missing NVIDIA Container Toolkit or GPU reservation | Install the toolkit and add the devices block |
Prometheus disk keeps growing | No retention limit | Set –storage.tsdb.retention.time or a size limit |
Histogram quantiles look wrong | Default buckets too small for LLM latency | Define buckets that match your real range |
Grafana loses settings on restart | No volume for /var/lib/grafana | Mount a volume and provision data sources |
Security and Performance Best Practices for AI Monitoring
- Bind all dashboards to localhost or a VPN, and turn on Grafana login with a strong admin password.
- Do not put prompts, user messages, or personal data into metric labels or logs.
- Keep 15 days of data to start, then raise retention if you need longer trends.
- Back up the Grafana volume, since your dashboards live there.
Frequently asked questions
How do I monitor Docker containers with Prometheus and Grafana?
Run cAdvisor as a container with access to the host’s Docker data, point a Prometheus scrape job at it, and add Prometheus as a data source in Grafana. Then import a container dashboard or build panels from metrics such as container_cpu_usage_seconds_total and container_memory_working_set_bytes. Add node_exporter to see host-level CPU, memory, and disk.
What is cAdvisor and do I need it?
cAdvisor is a Google-developed tool that collects resource usage for each running container and exposes it as Prometheus metrics. You need it if you want per-container CPU, memory, network, and restart data. Without it, Prometheus can only see the host as a whole.
How do I monitor GPU usage in Docker?
Install the NVIDIA Container Toolkit, then run the NVIDIA DCGM exporter in a container with GPU access. It exposes metrics such as GPU utilization, memory used, temperature, and power draw on port 9400. Add it as a Prometheus target and use an existing DCGM dashboard in Grafana.
Which metrics should I track for an LLM application?
Start with request latency, time to first token, error rate, requests in progress, and tokens used per model. Add GPU memory and utilization if you host the model yourself. These show speed, reliability, load, and cost, which are the four things that decide whether an AI service works for users.
Is Prometheus or Grafana better for monitoring?
They do different jobs and work together. Prometheus collects and stores metrics, and it evaluates alert rules. Grafana turns the stored data into dashboards and can also send alerts. For a Docker setup, you normally use both.