In this article, I will use k6 for load testing and upload the result to influxDB and use Grafana to read the database.
So, let's set up the program
mkdir load-testing
cd load-testing
touch docker-compose.yml
version: "3.9"
services:
influxdb:
image: influxdb:1.8.10
environment:
- INFLUXDB_DB=k6
grafana:
image: grafana/grafana
ports:
- "8000:3000"
environment:
- GF_AUTH_ANONYMOUS_ORG_ROLE=Admin
- GF_AUTH_ANONYMOUS_ENABLED=true
- GF_AUTH_BASIC_ENABLED=false
k6:
image: grafana/k6
environment:
- K6_OUT=influxdb=http://influxdb:8086/k6
volumes:
- ./script.js:/script.js
myserver:
build: .
image: myserver
Since I use docker compose and I need a server for k6 to do load test, so I have to add myserver
as a service in this docker-compose too.
Then I will get a Dockerfile
from my previous article.
mkdir Dockerfile
FROM golang:1.17-alpine AS builder
WORKDIR /app
COPY go.mod .
COPY go.sum .
RUN go mod download
COPY . .
RUN go build -o app
FROM alpine:latest
WORKDIR /
COPY --from=builder /app/app .
EXPOSE 8080
CMD ["/app"]
With this Dockerfile, I will create a Go module
go mod init goloadtest
touch main.go
package main
import (
"math/rand"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/", func(ctx *gin.Context) {
delay := rand.Intn(200) + 300
time.Sleep(time.Millisecond * time.Duration(delay))
ctx.String(http.StatusOK, "response was sent")
})
r.Run()
}
Don't forget to use go mod tidy
to generate the go.sum
file.
Now let's run this docker compose
docker compose up -d influxdb grafana server
While waiting, create a script.js
file`
touch script.js
import { sleep } from 'k6';
import http from 'k6/http';
export default function() {
const url = 'http://myserver:8080';
http.get(url);
sleep(1);
}
The server url is http://myserver:8080 due to config in the docker-compose.yml
file.
Then start load testing with
docker compose run --rm k6 run /script.js
Your load testing result will be put to influxdb, to get that information, visit grafana in localhost:8000
.
Click Add data source
and click InfluxDB
; in the HTTP section, set URL to http://influxdb:8086
and in the InfluxDB Details section, set Database to k6.
Then click Save & test, if it works, go back to the homepage.
Click the create icon (the second one) on the left menu, select Import
, type 2587
then click the first Load
button.
At the k6 section, select InfluxDB and click the pink Import
button.
Now you will see the result that you did load testing with k6.
To see more thing, edit the script.js
file (read this guide) and
try to do load testing again with
docker compose run --rm k6 run /script.js
Check the dashboard again, you will see the difference. Also, you can edit the Go code and rebuild the server with
docker compose up -d --build myserver
Feel free to use this to improve your application, thank you for reading!
sources