本项目提供了一个使用 Docker 容器运行 PProf 的解决方案,帮助开发者方便地进行性能剖析和分析。
docker pull dockerhub.schaefer.name/pprof:latest-amd64
pprof-config.yamladdress: ":8080"
pprofs:
- name: "Heap profile"
pattern: ".*\.heap"
contentTypes: ["application/octet-stream"]
subProcessProfile: true
type: "heap"
- name: "CPU profile"
pattern: ".*\.cpu"
contentTypes: ["text/plain"]
type: "cpu"
- name: "Goroutine profile"
pattern: ".*\.goroutine"
contentTypes: ["text/plain"]
type: "goroutine"
docker run -d --name pprof -p 8080:8080 -v $(pwd)/pprof-config.yaml:/etc/pprof/config.yaml dockerhub.schaefer.name/pprof:latest-amd64
# 在浏览器访问 http://:8080 或者 http://localhost:8080 如果在本机运行
import (
"fmt"
"log"
"net/http"
"github.com/google/pprof/agent"
)
func main() {
log.Println("Starting application on port 8081")
http.HandleFunc("/", handler)
http.ListenAndServe(":8081", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/debug/pprof" {
w.Header().Set("Content-Type", "application/octet-stream")
agent.Profile(r.Context(), w, agent.MainArgs{})
return
}
fmt.Fprintf(w, "Hello, World!")
}
# 分析 CPU 文件
curl -X POST http://localhost:8080/pprof/upload -F "file=@./testdata/gobench.cpu"
# 开启交互式 PProf UI(仅限 macOS)
curl -X POST http://localhost:8080/pprof/debug \
-H "Content-Type: application/json; charset=utf-8" \
-d '{"address":"http://localhost:8081/debug/pprof/"}'
{
"tool_name": "analyze_pprof",
"arguments": {
"profile_path": "./testdata/gobench.cpu",
"type": "cpu"
}
}
{
"tool_name": "generate_flamegraph",
"arguments": {
"profile_path": "./testdata/gobench.cpu",
"output_path": "./flame-graph.svg"
}
}
请确保在运行 PProf 容器之前已经拉取最新的镜像,并正确配置您的应用程序以生成相应的剖析文件。如遇问题,请参考官方文档或联系技术支持。