هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.
$ مستخدم عادي# بصلاحية root (أو مع sudo)
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 …
| Item | Value |
|---|---|
| Package | k6 (repository dl.k6.io) or the grafana/k6 container |
| Scripts | .js or .ts files |
| Outputs | summary on screen, --out json=…, Prometheus remote write, InfluxDB, Grafana Cloud |
| Test types | smoke, load, stress, spike, soak (endurance), breakpoint |
انتبه
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.
Install on RHEL, Rocky, Alma and Fedora
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 k6Or without installing: docker run --rm -i grafana/k6 run - < script.js.
First configuration: a realistic test
Users open the home page, search, and view a product; ramp up to 50 users, hold, ramp down:
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);
}| Part | Why |
|---|---|
stages | A ramp up, a steady phase and a ramp down — like real traffic. |
thresholds | The 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). |
check | Counts correct answers — "200 with a wrong body" is also an error. |
sleep | Think 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%Test types
| Type | What | Example settings |
|---|---|---|
| Smoke | Does the script work? Is the system OK with minimal load? | --vus 1 --duration 30s |
| Load | Normal and peak expected traffic. | stages to the expected users (above) |
| Stress | More than expected — where does it degrade? | stages to 2–3× peak |
| Spike | A sudden jump (campaign, news). | 0 → 500 VUs in 10 s |
| Soak | Normal load for hours — memory leaks, slow growth. | 2–8 hours at normal load |
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.jsWatch 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.
Daily use: CI and the real uses
A smoke test on every deploy to staging, a load test before releases:
perf-smoke:
stage: test
image:
name: grafana/k6:latest
entrypoint: [""]
script:
- k6 run --vus 5 --duration 1m -e BASE_URL="$STAGING_URL" load-test.jsReal 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.
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.
Update and remove
Fix common problems
| Problem | Cause | Fix |
|---|---|---|
dial: i/o timeout / many errors at the start | Target 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 % CPU | Not enough resources on the test machine. | Fewer VUs per machine, less logging, more generators. |
| Thresholds fail but the app looks fine | Unrealistic goals or one slow endpoint. | Read per-endpoint metrics (name tags); set SLO-based thresholds. |
| Results are too good to be true | Responses 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. |
Next steps
- Quick how-tos: Load test an API, Define an SLO.
- Command page: k6.
- At work: k6 and ab — load tests.
- See the effect on the servers: Prometheus, Grafana. Scale with HPA: CKA — Scale with HPA.
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.