GeekIt

k6命令速查

安装与运行参数、脚本结构与 API、scenarios 编排、thresholds 门禁、自定义指标、数据文件、输出集成与报错排查等 158 条命令

共 158 条命令 · 11 类场景 · 点击右侧图标可复制

命令 / 片段说明复制
k6 version查看版本,新特性与 vus 上限和版本强相关
k6 --help查看子命令列表
k6 run --help查看 run 的全部参数
brew install k6macOS 安装
apt install k6Debian/Ubuntu,需先加 Grafana 源
dnf install k6RHEL/Fedora 系安装
choco install k6Windows 安装
docker run --rm -i grafana/k6 run - < script.js容器运行并从标准输入读脚本
docker run --rm -v $PWD:/scripts grafana/k6 run /scripts/script.js挂载目录运行本地脚本
k6 inspect script.js只解析脚本并输出 options,不实际压测
k6 archive script.js把脚本与依赖打包成 tar,便于在别处执行
k6 cloud login --token xxx登录 Grafana Cloud k6,使用云端压测
k6 run script.js最小可用的执行命令,参数全在脚本 options 中
命令 / 片段说明复制
k6 run --vus 10 --duration 30s script.js临时覆盖虚拟用户数与时长,优先级高于脚本 options
k6 run -u 10 -d 30s script.js简写形式
k6 run -i 100 script.js按总迭代次数运行,跑完即结束
k6 run --stage 30s:10,1m:50,30s:0命令行方式定义爬坡阶段:时长:目标 VU
k6 run -e BASE_URL=https://api.example.com script.js注入环境变量,脚本内用 __ENV.BASE_URL 读取
k6 run --tag env=test --tag version=v1 script.js给所有请求打标签,便于按维度过滤指标
k6 run --summary-export summary.json script.js导出汇总指标,便于 CI 解析
k6 run --out json=result.json script.js逐点输出原始指标,体积较大
k6 run --out csv=result.csv script.js输出 CSV,便于表格分析
k6 run --http-debug script.js打印请求头与响应头,排查鉴权与重定向
k6 run --http-debug=full script.js连响应体一起打印,注意日志量
k6 run --quiet script.js只输出最终汇总,减少日志噪音
k6 run --no-color script.js关闭彩色输出,适配 CI 日志
k6 run --linger script.js结束后保留连接,等 dashboard 拉取完数据
k6 run --no-thresholds script.js临时忽略阈值,用于调参阶段
k6 run --summary-mode=full script.js控制汇总输出详略,可选 full/compact/disabled
k6 run --throw script.js脚本异常立即失败,避免错误被吞掉
echo $?阈值失败时退出码为 99,可直接做 CI 门禁
命令 / 片段说明复制
import http from "k6/http"; import { check, sleep } from "k6";最常用三件套:HTTP 客户端、断言、思考时间
export const options = { vus: 10, duration: "30s", };脚本内声明压测配置,命令行可覆盖
export default function () { http.get("https://example.com/"); sleep(1); }每个 VU 循环执行的入口函数
export function setup() { return { token: "abc" }; }压测前执行一次,返回值传给默认函数
export default function (data) { http.get(__ENV.URL, { headers: { Authorization: data.token } }); }接收 setup 返回值,避免每个 VU 重复登录
export function teardown(data) { console.log("done"); }压测结束后执行一次,用于清理数据
export function handleSummary(data) { return { "summary.json": JSON.stringify(data) }; }自定义输出文件,替代默认汇总打印
const res = http.post(url, body, { headers: { "Content-Type": "application/json" } });POST JSON,body 传字符串
http.get(url, { tags: { name: "home" } });给单个请求打标签,指标按 name 聚合
http.get(url, { timeout: "5s", redirects: 0 });设置超时与不跟随重定向
const res = http.get(url, { responseType: "text" });指定响应解析方式,默认 text
check(res, { "status is 200": (r) => r.status === 200 });断言状态码,结果计入 checks 指标
check(res, { "body ok": (r) => r.json("code") === 0, "fast": (r) => r.timings.duration < 500, });一次多个断言,按名称分别统计通过率
res.timings.duration单请求总耗时,单位毫秒
http.batch([ ["GET", url1], ["GET", url2], ]);并发请求多个 URL,模拟页面资源加载
group("login", () => { http.post(loginUrl, payload); });分组统计,汇总里按组展示耗时
sleep(Math.random() * 2 + 1);随机思考时间,避免所有 VU 同时打点
console.log("vu:", __VU, "iter:", __ITER);输出当前 VU 与迭代序号,调试脚本用
__ENV.BASE_URL || "http://localhost"读取环境变量并提供默认值
命令 / 片段说明复制
scenarios: { smoke: { executor: "constant-vus", vus: 5, duration: "30s" }, }固定 VU 数,最常用的基线场景
{ executor: "shared-iterations", vus: 20, iterations: 1000 }总迭代次数在所有 VU 间共享
{ executor: "per-vu-iterations", vus: 20, iterations: 50 }每个 VU 固定跑 N 次
{ executor: "constant-arrival-rate", rate: 200, timeUnit: "1s", duration: "1m", preAllocatedVUs: 50, maxVUs: 200, }恒定到达率,等价于 wrk2 的开环压测
{ executor: "ramping-vus", startVUs: 0, stages: [ { duration: "30s", target: 20 }, { duration: "1m", target: 100 }, { duration: "20s", target: 0 }, ], }VU 爬坡,适合观察系统随压力变化的曲线
{ executor: "ramping-arrival-rate", startRate: 10, timeUnit: "1s", stages: [{ duration: "1m", target: 500 }], preAllocatedVUs: 50, maxVUs: 500, }到达率爬坡,容量评估的首选场景
{ executor: "externally-controlled", vus: 10, maxVUs: 100, duration: "10m" }通过 REST API 动态调整压力
startTime: "30s"让多个场景错峰开始,模拟混合业务
exec: "loginFlow"场景绑定到脚本内某个导出函数
gracefulStop: "10s"结束时给正在跑的迭代留出收敛时间
tags: { scenario: "read" }场景级标签,指标可按场景拆分
env: { RATE: "100" }场景级环境变量,避免多场景互相干扰
preAllocatedVUs 要按 R × 延迟估算给少了会出现 dropped_iterations,到达率跑不满
--vus 与 scenarios 不能同时使用混用会报配置冲突,二选一
命令 / 片段说明复制
thresholds: { http_req_duration: ["p(95)<500", "p(99)<1000"], }最常见的延迟 SLA 门禁
thresholds: { http_req_failed: ["rate<0.01"] }错误率低于 1% 才算通过
thresholds: { checks: ["rate>0.99"] }断言通过率门禁
thresholds: { http_reqs: ["rate>500"] }要求吞吐达到下限,防止"压不出量"也算通过
thresholds: { iterations: ["count>1000"] }要求完成足够迭代数
"http_req_duration{status:200}": ["p(95)<300"]按标签过滤,只统计成功请求的延迟
"http_req_duration{name:home}": ["p(99)<800"]按请求名分别设阈值
thresholds: { http_req_duration: [{ threshold: "p(95)<500", abortOnFail: true, delayAbortEval: "10s" }], }阈值一破立即中止,避免继续打挂系统
thresholds: { my_trend: ["avg<200"] }自定义指标同样可设阈值
summaryTrendStats: ["avg", "med", "p(90)", "p(95)", "p(99)", "p(99.9)", "max"]控制汇总里显示哪些分位
阈值失败退出码为 99CI 中直接判断退出码即可
k6 run --no-thresholds script.js调参阶段临时关闭阈值检查
命令 / 片段说明复制
http_reqs总请求数,rate 即 QPS
http_req_duration请求总耗时,看 p(95)/p(99)
http_req_waiting等待首字节时间,最接近服务端处理耗时
http_req_connecting建连耗时,偏高说明网络或 TCP 层问题
http_req_tls_handshakingTLS 握手耗时,HTTPS 压测重点关注
http_req_sending / http_req_receiving发送与接收耗时,大 body 场景有用
http_req_blocked等待可用连接的时间,偏高说明连接数不足
http_req_failed失败率,含 4xx/5xx 与网络错误
iteration_duration单次迭代总耗时,含 sleep
dropped_iterations因 VU 不足被丢弃的迭代,非 0 说明到达率没跑满
vus / vus_max当前活跃 VU 与上限
data_received / data_sent网络流量,评估带宽占用
import { Trend, Rate, Counter, Gauge } from "k6/metrics";自定义指标需要引入的类型
const loginTime = new Trend("login_time");定义趋势指标
loginTime.add(res.timings.duration, { flow: "login" });写入数据并附带标签
const successRate = new Rate("biz_success");定义比率指标
successRate.add(res.json("code") === 0);直接传入布尔值
const errCount = new Counter("biz_error_total");定义计数指标
const qpsNow = new Gauge("current_qps");定义瞬时值指标
new Trend("x", true)第二个参数为 true 表示该值以毫秒计入汇总
命令 / 片段说明复制
import { SharedArray } from "k6/data"; const users = new SharedArray("users", () => JSON.parse(open("./users.json")));所有 VU 共享同一份数据,避免内存暴涨
const user = users[__VU % users.length];按 VU 取不同数据,模拟多用户
import papaparse from "https://jslib.k6.io/papaparse/5.1.1/index.js"; const rows = papaparse.parse(open("./data.csv"), { header: true }).data;CSV 参数化,k6 无内置 CSV 解析
import { randomString, randomIntBetween } from "https://jslib.k6.io/k6-utils/1.2.0/index.js";常用工具函数:随机字符串与随机整数
import { htmlReport } from "https://raw.githubusercontent.com/benc-uk/k6-reporter/main/dist/bundle.js";生成 HTML 报告,需要网络可访问该地址
return { "report.html": htmlReport(data) };在 handleSummary 中返回,运行结束即生成报告
import exec from "k6/execution"; exec.vu.idInTest执行上下文,取 VU 与迭代信息
import { randomBytes } from "k6/crypto";crypto 模块,生成随机字节或计算摘要
open("./payload.json")在 init 阶段读取本地文件,只能读一次
文件必须在 k6 archive 中包含远程执行前先 archive 打包,否则 open 会失败
SharedArray 不能修改元素只读共享,需可变数据请用普通数组 + init 上下文
命令 / 片段说明复制
k6 run --summary-export=summary.json script.js导出汇总,CI 中最常用的方式
k6 run --out json=result.json script.js逐指标点数据,可用于二次分析
k6 run --out csv=result.csv script.jsCSV 输出,直接进 Excel 或 BI
k6 run --out influxdb=http://localhost:8086/k6 script.js写 InfluxDB,配合 Grafana 看趋势
K6_PROMETHEUS_RW_SERVER_URL=http://localhost:9090/api/v1/write k6 run --out experimental-prometheus-rw script.js远程写 Prometheus,做长期观测
K6_WEB_DASHBOARD=true k6 run script.js开启内置 Web 仪表盘,浏览器实时看曲线
K6_WEB_DASHBOARD_EXPORT=report.html k6 run script.js结束时导出 HTML 报告
k6 cloud run script.js在 Grafana Cloud k6 上分布式执行
k6 run --out dashboard=report.html script.js新版本可用 dashboard 输出器直接导出报告
--summary-time-unit=ms统一汇总时间单位,便于横向对比
把 summary.json 解析为 QPS/P95/错误率写入流水线CI 中做趋势与门禁的常见做法
命令 / 片段说明复制
checks断言总数与通过率,低于 100% 说明有功能性失败
http_req_failed: rate=0.00%失败率,超过阈值会直接判失败
http_req_duration: p(95)=120ms用户体感的核心指标
http_req_duration: p(99)=450ms尾部延迟,长尾问题看这里
http_reqs: 30000 1234.5/s总请求数与实测 QPS
iterations: 5000 205.6/s完成迭代数与速率
vus: 10 min=10 max=10确认实际并发是否达到配置值
dropped_iterations 非 0VU 不足,提高 preAllocatedVUs 与 maxVUs
http_req_blocked 偏高连接池不够,调大 VU 或开启连接复用
http_req_connecting 偏高网络 RTT 或 TCP 握手慢,检查链路与 noConnectionReuse
thresholds 段落显示 ✓ / ✗直接说明门禁是否通过
exit code 99阈值未通过,CI 应据此失败
命令 / 片段说明复制
k6 inspect script.js检查脚本能否解析、options 是否生效
k6 run --http-debug=full script.js看完整请求与响应,定位鉴权与参数问题
console.log(JSON.stringify(res.headers))打印响应头,确认返回结构
console.log(res.status, res.body.slice(0, 200))只打前 200 字符,避免刷屏
k6 run --throw script.js把脚本异常当作失败,避免静默通过
k6 run --no-color --quiet script.jsCI 环境减少噪音,只看结果
k6 run --linger script.js浏览器 dashboard 还没看完就结束时使用
k6 run --no-usage-report script.js关闭使用数据上报,内网环境常用
K6_NO_USAGE_REPORT=true用环境变量关闭上报
在 init 阶段做静态校验如必填环境变量缺失就 throw,避免跑到一半才失败
命令 / 片段说明复制
SyntaxError: Unexpected token "export"脚本被 node 执行了,必须用 k6 run
require is not supportedk6 用 ESM,改 import 语法
Cannot find module "k6/http"同上,运行方式错误
dial tcp 10.0.0.5:80: connect: connection refused端口未监听或被防火墙拦截
context deadline exceeded请求超时,检查接口耗时或调大 timeout
x509: certificate signed by unknown authority自签证书需 insecureSkipTLSVerify: true
the server gave HTTP response to HTTPS client地址写成 https 但服务端是明文
thresholds on metrics ... have been crossed阈值未通过,按提示定位是延迟还是错误率
dropped_iterations 持续增长到达率高于实际处理能力或 VU 预分配不足
--vus 与 scenarios 冲突两者不能同时存在,删掉其一
invalid options: unknown fieldoptions 里有拼写错误或该版本不支持的字段
unsupported executor执行器名拼错,或版本过低不支持该执行器
no such file or directory (open)open 的文件路径错误,或 archive 时未包含
404 拉取 jslib 模块失败内网无法访问外链,改为本地文件或私有仓库
k6: command not found未安装或不在 PATH
脚本跑完但没有汇总用了 --quiet 或 --summary-mode=disabled
VU 数上不去到 maxVUs 上限或系统句柄/端口不足
http_req_failed 高但接口返回 200检查是否 3xx 重定向或连接被中途关闭

运维常用组合

最小可用脚本import http from "k6/http"; import { check, sleep } from "k6"; export const options = { vus: 10, duration: "30s", thresholds: { http_req_duration: ["p(95)<500"] } }; export default function () { check(http.get(__ENV.URL), { ok: (r) => r.status === 200 }); sleep(1); }
恒定到达率容量测试options.scenarios.rps2000 = { executor: "constant-arrival-rate", rate: 2000, timeUnit: "1s", duration: "1m", preAllocatedVUs: 200, maxVUs: 800 }; k6 run script.js
爬坡找拐点ramping-arrival-rate 从 10 爬到 500 → 每阶段 1 分钟 → 观察 http_req_duration p(99) 与 http_req_failed 变化 → 找拐点
CI 性能门禁k6 run --summary-export=summary.json --quiet script.js → 判断退出码 99 → 解析 summary.json 上传归档
HTML 报告handleSummary 中返回 { "report.html": htmlReport(data) } → 运行结束生成 → 附到构建产物
趋势观测K6_PROMETHEUS_RW_SERVER_URL=... k6 run --out experimental-prometheus-rw script.js → Grafana 看 QPS/P95 长期曲线

实战要点

1. 配置写进脚本

options 与脚本放在一起才能版本化,命令行只用于临时覆盖

2. 容量评估用到达率

constant-arrival-rate 才是开环压测,constant-vus 是闭环

3. 阈值就是门禁

把 P95、错误率写成 thresholds,CI 用退出码 99 判断失败

4. 盯 dropped_iterations

非 0 说明压力没打满,结论会偏乐观,先补 VU 再谈性能

5. setup 做一次登录

把 token 通过返回值分发,避免每个 VU 重复登录压垮认证服务

6. 大数据用 SharedArray

普通数组会被每个 VU 复制一份,内存会迅速爆掉

共 158 条 k6 命令 · 示例中的域名、速率与文件路径请替换为实际环境

关于k6命令速查

在线 k6 命令速查手册,按安装与版本、基础运行、脚本结构、场景 scenarios、阈值 thresholds、指标与自定义 metric、数据与工具库、结果输出与集成、结果解读、调试与排错、常见报错等 11 类场景整理 150 余条常用命令与脚本片段,每条附中文说明与可直接复制的写法,支持关键词搜索、分类折叠和一键复制,打开网页即可查阅。涵盖 k6 version 与 brew/apt/dnf/choco/docker 安装与 k6 run/inspect/archive/cloud 子命令、run 的 --vus/-u 与 --duration/-d 与 --iterations/-i 与 --stage 与 -e 环境变量 与 --tag 与 --summary-export 与 --out json/csv/influxdb 与 --http-debug/--http-debug=full 与 --quiet 与 --linger 与 --no-thresholds 与 --summary-mode、脚本的 import http from k6/http 与 check/sleep/group 与 options 的 vus/duration/iterations/stages/scenarios/thresholds/tags/gracefulStop/discardResponseBodies/summaryTrendStats 与 default/setup/teardown/handleSummary 导出函数、http.get/post/put/patch/del 与 request 与 batch 与 params 的 headers/tags/timeout/redirects/responseType 与 res.timings/status/json()/body、scenarios 的 constant-vus/shared-iterations/per-vu-iterations/constant-arrival-rate/ramping-vus/ramping-arrival-rate/externally-controlled 与 rate/timeUnit/preAllocatedVUs/maxVUs/startTime/gracefulStop/exec、thresholds 的 p(95)<500 与 rate<0.01 与 {status:200} 标签过滤 与 abortOnFail/delayAbortEval 与退出码 99、内置指标 http_reqs/http_req_duration/http_req_waiting/http_req_connecting/http_req_tls_handshaking/http_req_failed/iteration_duration/iterations/vus/vus_max/data_received/data_sent/checks/dropped_iterations 与 Trend/Rate/Counter/Gauge 自定义指标、SharedArray 与 papaparse CSV 与 randomString 工具库与 htmlReport 报告生成、web-dashboard 与 InfluxDB/Prometheus/Grafana Cloud 集成,以及 SyntaxError Unexpected token export、require is not supported、dial tcp connection refused、context deadline exceeded、x509 certificate signed by unknown authority(insecureSkipTLSVerify)、thresholds have been crossed、dropped_iterations 过高、--vus 与 scenarios 冲突、Cannot find module k6/http、no such file 等报错排查。适用于 HTTP 接口与多接口链路压测、脚本化场景编排与参数化、恒定到达率容量评估、SLA 阈值门禁接入 CI、压测结果可视化与长期趋势观测,以及运维、测试与后端工程师面试复习。

核心能力

  • 涵盖 k6 version 与 brew/apt/dnf/choco/docker 安装与 k6 run/inspect/archive/cloud 子命令、run 的 --vus/-u 与 --duration/-d 与 --iterations/-i 与 --stage 与 -e 环境变量 与 --tag 与 --summary-export 与 --out json/csv/influxdb 与 --http-debug/--http-debug=full 与 --quiet 与 --linger 与 --no-thresholds 与 --summary-mode、脚本的 import http from k6/http 与 check/sleep/group 与 options 的 vus/duration/iterations/stages/scenarios/thresholds/tags/gracefulStop/discardResponseBodies/summaryTrendStats 与 default/setup/teardown/handleSummary 导出函数、http.get/post/put/patch/del 与 request 与 batch 与 params 的 headers/tags/timeout/redirects/responseType 与 res.timings/status/json()/body、scenarios 的 constant-vus/shared-iterations/per-vu-iterations/constant-arrival-rate/ramping-vus/ramping-arrival-rate/externally-controlled 与 rate/timeUnit/preAllocatedVUs/maxVUs/startTime/gracefulStop/exec、thresholds 的 p(95)<500 与 rate<0.01 与 {status:200} 标签过滤 与 abortOnFail/delayAbortEval 与退出码 99、内置指标 http_reqs/http_req_duration/http_req_waiting/http_req_connecting/http_req_tls_handshaking/http_req_failed/iteration_duration/iterations/vus/vus_max/data_received/data_sent/checks/dropped_iterations 与 Trend/Rate/Counter/Gauge 自定义指标、SharedArray 与 papaparse CSV 与 randomString 工具库与 htmlReport 报告生成、web-dashboard 与 InfluxDB/Prometheus/Grafana Cloud 集成,以及 SyntaxError Unexpected token export、require is not supported、dial tcp connection refused、context deadline exceeded、x509 certificate signed by unknown authority(insecureSkipTLSVerify)、thresholds have been crossed、dropped_iterations 过高、--vus 与 scenarios 冲突、Cannot find module k6/http、no such file 等报错排查

适用场景

适用于 HTTP 接口与多接口链路压测、脚本化场景编排与参数化、恒定到达率容量评估、SLA 阈值门禁接入 CI、压测结果可视化与长期趋势观测,以及运维、测试与后端工程师面试复习。k6命令速查全程在浏览器中完成,无需安装插件,可放心用于日常办公与排障。

常见问题

k6命令速查是免费的吗?需要注册或安装吗?
k6命令速查完全免费,无需注册、无需下载安装任何软件,用浏览器打开网页即可直接使用,也不限制使用次数。
k6命令速查支持哪些功能?
涵盖 k6 version 与 brew/apt/dnf/choco/docker 安装与 k6 run/inspect/archive/cloud 子命令、run 的 --vus/-u 与 --duration/-d 与 --iterations/-i 与 --stage 与 -e 环境变量 与 --tag 与 --summary-export 与 --out json/csv/influxdb 与 --http-debug/--http-debug=full 与 --quiet 与 --linger 与 --no-thresholds 与 --summary-mode、脚本的 import http from k6/http 与 check/sleep/group 与 options 的 vus/duration/iterations/stages/scenarios/thresholds/tags/gracefulStop/discardResponseBodies/summaryTrendStats 与 default/setup/teardown/handleSummary 导出函数、http.get/post/put/patch/del 与 request 与 batch 与 params 的 headers/tags/timeout/redirects/responseType 与 res.timings/status/json()/body、scenarios 的 constant-vus/shared-iterations/per-vu-iterations/constant-arrival-rate/ramping-vus/ramping-arrival-rate/externally-controlled 与 rate/timeUnit/preAllocatedVUs/maxVUs/startTime/gracefulStop/exec、thresholds 的 p(95)<500 与 rate<0.01 与 {status:200} 标签过滤 与 abortOnFail/delayAbortEval 与退出码 99、内置指标 http_reqs/http_req_duration/http_req_waiting/http_req_connecting/http_req_tls_handshaking/http_req_failed/iteration_duration/iterations/vus/vus_max/data_received/data_sent/checks/dropped_iterations 与 Trend/Rate/Counter/Gauge 自定义指标、SharedArray 与 papaparse CSV 与 randomString 工具库与 htmlReport 报告生成、web-dashboard 与 InfluxDB/Prometheus/Grafana Cloud 集成,以及 SyntaxError Unexpected token export、require is not supported、dial tcp connection refused、context deadline exceeded、x509 certificate signed by unknown authority(insecureSkipTLSVerify)、thresholds have been crossed、dropped_iterations 过高、--vus 与 scenarios 冲突、Cannot find module k6/http、no such file 等报错排查。
k6命令速查适合哪些场景使用?
适用于 HTTP 接口与多接口链路压测、脚本化场景编排与参数化、恒定到达率容量评估、SLA 阈值门禁接入 CI、压测结果可视化与长期趋势观测,以及运维、测试与后端工程师面试复习。