Geavanceerd
Zoeken inInstallatiegidsen
Zo zoek je
  • Plak een foutmelding tussen aanhalingstekens, bijv. "permission denied", om de oplossingstabel te vinden.
  • Kies een gebied en een deel van de gids (installeren, eerste instellingen, dagelijks gebruik, beveiliging, oplossingen) om direct naar de juiste stap te gaan.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

Gids 86k6 · Monitoring

Install and use k6 (load testing)

k6 (by Grafana Labs) runs load tests as code: you write a small JavaScript (or TypeScript) file that describes what virtual users do, how many there are and what "good" means (for example "95 % of requests under 500 ms, less than 1 % errors"). k6 runs it from the command line, prints clear results and fails the run when the limits are broken — perfect for CI. This guide installs k6 on RHEL and Ubuntu, writes a realistic test with stages, checks and thresholds, explains the test types, and sends results to Prometheus/Grafana.

  • 11 Lessen
  • 6 Commando's

Dit deel is nog niet vertaald. Je ziet de Engelse tekst.

$ als gewone gebruiker# als root (of met sudo)

86.1

Know it before you install

VUs (virtual users) run your script in a loop. Stages change the number of VUs over time. Checks test each response (status, body). Thresholds are the pass/fail rules for the whole test (exit code 99 when a threshold fails). Built-in metrics: http_req_duration, http_req_failed, iterations, vus …

ItemValue
Packagek6 (repository dl.k6.io) or the grafana/k6 container
Scripts.js or .ts files
Outputssummary on screen, --out json=…, Prometheus remote write, InfluxDB, Grafana Cloud
Test typessmoke, load, stress, spike, soak (endurance), breakpoint

Let op

Load tests can take a service down. Test only systems you own, preferably a staging copy, and tell the team (and the hosting/CDN provider if needed) before big tests.

Commando's in deze les

86.2

Install on RHEL, Rocky, Alma and Fedora

dnf -y install https://dl.k6.io/rpm/repo.rpm
dnf -y install k6
k6 version

Commando's in deze les

86.3

Install on Ubuntu and Debian

gpg -k
gpg --no-default-keyring --keyring /usr/share/keyrings/k6-archive-keyring.gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys C5AD17C747E3415A3642D57D77C6C491D6AC1D69
echo "deb [signed-by=/usr/share/keyrings/k6-archive-keyring.gpg] https://dl.k6.io/deb stable main" > /etc/apt/sources.list.d/k6.list
apt-get update
apt-get install -y k6

Or without installing: docker run --rm -i grafana/k6 run - < script.js.

86.4

First configuration: a realistic test

Users open the home page, search, and view a product; ramp up to 50 users, hold, ramp down:

load-test.js
import http from "k6/http";
import { check, sleep, group } from "k6";
 
const BASE = __ENV.BASE_URL || "https://staging.shop.example.com";
 
export const options = {
  stages: [
    { duration: "1m", target: 10 },
    { duration: "3m", target: 50 },
    { duration: "5m", target: 50 },
    { duration: "1m", target: 0 },
  ],
  thresholds: {
    http_req_failed: ["rate<0.01"],
    http_req_duration: ["p(95)<500", "p(99)<1500"],
    "http_req_duration{name:search}": ["p(95)<800"],
    checks: ["rate>0.99"],
  },
};
 
export default function () {
  group("browse", () => {
    const home = http.get(`${BASE}/`);
    check(home, { "home 200": (r) => r.status === 200 });
 
    const search = http.get(`${BASE}/api/search?q=racket`, { tags: { name: "search" } });
    check(search, {
      "search 200": (r) => r.status === 200,
      "search has results": (r) => r.json("total") > 0,
    });
 
    const product = http.get(`${BASE}/api/products/42`, { tags: { name: "product" } });
    check(product, { "product 200": (r) => r.status === 200 });
  });
  sleep(Math.random() * 2 + 1);
}
PartWhy
stagesA ramp up, a steady phase and a ramp down — like real traffic.
thresholdsThe goals (SLOs). If one fails, k6 exits with code 99 — the CI job fails.
tags: { name: … }Groups URLs with IDs into one metric (and allows per-endpoint thresholds).
checkCounts correct answers — "200 with a wrong body" is also an error.
sleepThink time, so 50 VUs behave like 50 real users, not a flood.
k6 run -e BASE_URL=https://staging.shop.example.com load-test.js
     ✓ http_req_duration..............: avg=182ms  p(95)=341ms  p(99)=902ms
     ✓ http_req_failed................: 0.12%
     ✓ checks.........................: 99.87%

86.5

Test types

TypeWhatExample settings
SmokeDoes the script work? Is the system OK with minimal load?--vus 1 --duration 30s
LoadNormal and peak expected traffic.stages to the expected users (above)
StressMore than expected — where does it degrade?stages to 2–3× peak
SpikeA sudden jump (campaign, news).0 → 500 VUs in 10 s
SoakNormal load for hours — memory leaks, slow growth.2–8 hours at normal load
k6 run --vus 1 --duration 30s load-test.js
k6 run --vus 200 --duration 2m load-test.js

Commando's in deze les

86.6

Results in Prometheus and Grafana

Send metrics live to Prometheus (started with --web.enable-remote-write-receiver) and use the k6 Grafana dashboard:

K6_PROMETHEUS_RW_SERVER_URL=http://prometheus.example.com:9090/api/v1/write K6_PROMETHEUS_RW_TREND_STATS="p(95),p(99),avg" k6 run -o experimental-prometheus-rw load-test.js
k6 run --out json=results.json load-test.js
k6 run --summary-export=summary.json load-test.js

Watch the server side at the same time (CPU, memory, DB, error logs) — the test tells you that it is slow; server metrics tell you why.

Commando's in deze les

86.7

Daily use: CI and the real uses

A smoke test on every deploy to staging, a load test before releases:

.gitlab-ci.yml
perf-smoke:
  stage: test
  image:
    name: grafana/k6:latest
    entrypoint: [""]
  script:
    - k6 run --vus 5 --duration 1m -e BASE_URL="$STAGING_URL" load-test.js

Real uses at work:

  • Check that a release still meets the latency SLO before production.
  • Find the breaking point and size servers/autoscaling (HPA) with real numbers.
  • Test rate limits, caches and CDN behaviour.

86.8

Make it safe

Security checklist:

  • Only your own systems, staging first; agree on time windows for big tests.
  • Use test accounts and test data; never real customer accounts or payments.
  • Secrets (tokens) from environment variables (__ENV), not in the script in Git.
  • Start small (smoke), then grow; have a stop plan (Ctrl+C stops k6; know who watches the system).
  • Large tests from several load generators or a cloud service — one laptop's network is often the limit.

86.9

Update and remove

dnf -y upgrade k6
apt-get install --only-upgrade -y k6
dnf -y remove k6

Commando's in deze les

86.10

Fix common problems

ProblemCauseFix
dial: i/o timeout / many errors at the startTarget not reachable, firewall/WAF, or too many VUs at once.Smoke test first; allow the load generator IP; ramp up slowly.
The load generator is at 100 % CPUNot enough resources on the test machine.Fewer VUs per machine, less logging, more generators.
Thresholds fail but the app looks fineUnrealistic goals or one slow endpoint.Read per-endpoint metrics (name tags); set SLO-based thresholds.
Results are too good to be trueResponses cached by a CDN, or errors returned fast.Add checks on the body; bypass the CDN when you test the origin.
Too many metric series (one per URL)URLs with IDs.Use tags: { name: "…" } for dynamic URLs.

86.11

Next steps

1What makes a k6 run fail in CI?

A failed threshold — k6 then exits with code 99.

2Why use tags: { name: … } on URLs with IDs?

So all /products/1, /products/2 … requests are measured together as one endpoint.

Commando's in deze les

Alle commando's in dit hoofdstuk