背景:
在 Kubernetes 集群中部署容器化应用时,若依赖的远程数据源出现异常且无法在本地测试环境模拟相同数据条件,可能导致问题难以在开发环境中重现。此时,需要使用远程 dlv 调试技术对生产环境中的容器实例进行实时诊断和问题追踪。
实现过程:
本文以 deployment 方式实现该功能:
一、修改 YAML 配置文件
方式一:Sidecar 模式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
| apiVersion: apps/v1
kind: Deployment
metadata:
name: xxxname
namespace: namespace
spec:
replicas: 1
selector:
matchLabels:
xxx: xxx
template:
metadata:
labels:
xxx: xxx
spec:
containers:
# 主应用容器 - 添加调试环境变量
- name: xxxname
command:
- ./startapp
- --config-file=/xxxx
image: xxx
env:
- name: GODEBUG
value: "gctrace=1"
- name: GOMAXPROCS
value: "2"
ports:
- containerPort: 8888
name: before_biz_port
protocol: TCP
# 添加调试端口
- containerPort: 2345
name: dlv-debug
protocol: TCP
resources:
requests:
cpu: 500m
memory: 1Gi
limits:
cpu: 1000m
memory: 2Gi
# Delve 调试 Sidecar
- name: dlv-debugger
image: golang:1.21-alpine
command:
- /bin/sh
- -c
- |
apk add --no-cache git
go install github.com/go-delve/delve/cmd/dlv@latest
/go/bin/dlv attach 1 --headless --listen=:2345 --api-version=2 --accept-multiclient --log
securityContext:
capabilities:
add:
- SYS_PTRACE
privileged: false
runAsUser: 0
ports:
- containerPort: 2345
name: dlv-debug
protocol: TCP
volumeMounts:
- mountPath: /logs
name: logs
readOnly: true
volumes:
- emptyDir: {}
name: logs
|
方式二:直接集成模式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| # 在主容器中集成调试功能
- name: xxx
command:
- /bin/sh
- -c
- |
# 安装 delve(如镜像中未包含)
if ! command -v dlv &> /dev/null; then
go install github.com/go-delve/delve/cmd/dlv@latest
fi
# 使用 delve 启动程序
/go/bin/dlv exec --headless --listen=:2345 --api-version=2 --accept-multiclient \
./xxx -- \
--config-file=/xxx
securityContext:
capabilities:
add:
- SYS_PTRACE
ports:
- containerPort: 8888
name: before_biz_port
protocol: TCP
- containerPort: 2345
name: dlv-debug
protocol: TCP
|
关键参数说明:
attach 1:附加到 PID 为 1 的进程(Kubernetes 容器中的主进程)--headless:无头模式,仅运行调试服务器--listen=:2345:监听 2345 端口--api-version=2:使用 JSON-RPC API 版本 2--accept-multiclient:允许多个调试客户端连接--log:启用调试日志输出
二、本地端口转发
1
| kubectl port-forward deployment/xxx 2345:2345 -n name_space
|