前言
之前搬運了一個youtube視頻,學習了一波大佬講解的用vscode來debug容器的技巧,yyds!
本篇來做個簡單的記錄,希望集成至少三篇以上的vscode debug技巧,包括并不限于:
編程語言debug
容器debug
k8s debug
廢話不多說,直接從第二篇開始,有空了更新其他的debug技巧!
準備
dockerfile和python腳本(PS:看看這發量,肯定值得學習一波!)
假設上面的容器已經跑起來了,名稱為dalaoyyds~
詳解
上面的教程分為三個步驟,一步一步帶你debug!
entrypoint
debug方法是啟動一個entrypoint=bash的容器:
docker run -i -d --entrypoint=bash dalaoyyds(容器id)
使用exec可以進入容器執行操作:
docker exec -it bashcontainerid(上面那個容器返回的容器id)
接著你就可以do whatever you like。
cp
緊接上面的entrypoint操作,在容器內部執行命令后,使用cp將產出的結果復制到容器外面:
docker cp xxxx:/src/time.txt ./src/time.txt.Container
debugger
將上面的dockerfile作為基礎模板,新增一個debugger鏡像,安裝debupy插件,然后使用ENTRYPOINT暴露一個服務端口。
外部,使用-p 5678:5678來將主機和容器網絡打通,一般默認情況,使用的是bridge network模式:
docker run -p 5678:5678 xxx unitest
vscode插件真香
使用python remote attach插件, 前提是的項目下有py文件,會自動偵探,如果沒能自動識別,檢查安裝了python插件。
打上斷點后,就能在左側顯示locals變量值了。
golang debug
視頻中的方法介紹了python的debug技巧,我們能debug其他編程語言嗎?
以下拋磚引玉介紹下go語言容器debug。
Windows workspace debug Remote containers
第一步,安裝vscode、vscode remote containers extension、docker和docker-compose。remote-containers擴展在vscode擴展安裝,該插件是啟動遠程容器來debug本地代碼,遠程連接方式一般采用ssh。一般采用windows連接遠程linux服務器。
第二步,配置devcontainer demo,并按需修改:
https://github.com/qdm12/godevcontainer/tree/master/.devcontainer
第三步,選擇Remote-Containers: Open Folder in Container..
通過以上設置就能開啟remote debug。
以上的方案適用于本地的Windows來debug遠程容器,本地需要安裝docker desktop和wsl程序。
Linux workspace debug local containers
也可以選擇安裝linux版本的vscode,來完成以上操作。
dlv
就我個人而言,一般都是使用vscode來ssh遠程linux主機開發。
插件:remote-ssh
在這種情況下,可以使用golang的debug神器dlv,在容器中安裝待debug的二進制包和dlv,編輯主機到容器的映射關系config.yml,外部用vscode連接暴露的服務, 即可開始調試功能。
lauch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Remote Debug",
"type": "go",
"request": "launch",
"mode": "remote",
"remotePath": "",
"port": 2000,
"host": "127.0.0.1",
"program": "${workspaceRoot}/cloud/cmd/cloudcore/cloudcore.go",
"showLog": true,
"env": {},
"args": []
}
]
}
config.yml
substitute-path:
- {from: /, to: /root/go/src/github.com/kubeedge}
dockerfile
ENV CGO_ENABLED 0
COPY . /go/src/github.com/kubeedge/kubeedge
RUN go build -gcflags "all=-N -l" -o /server github.com/kubeedge/kubeedge/cloud/cmd/cloudcore
# Compile Delve
RUN apk add --no-cache git
RUN go get github.com/derekparker/delve/cmd/dlv
FROM alpine:3.11
EXPOSE 8080 2000
# Allow delve to run on Alpine based containers.
RUN apk add --no-cache libc6-compat
WORKDIR /
COPY --from=build-env /server /
COPY --from=build-env /go/bin/dlv /
COPY ./config.yml ./
# 啟動服務的配置文件, 按需添加
COPY cloudcore.yaml /etc/kubeedge/config/cloudcore.yaml
COPY /root/.kube/config /root/.kube/config
# Run delve
#CMD ["/dlv", "--listen=:40000", "--headless=true", "--api-version=2", "exec", "/server"]
#/dlv --listen=:40000 --headless=true --api-version=2 exec /server
CMD ["/bin/sh"]
docker run
docker run -it --rm --name cloudcore --security-opt="seccomp=unconfined" --cap-add=SYS_PTRACE -p 2000:2000 cloudcore-debugger:latest sh
通過以上配置就能開啟調試模式。
PS: 碼字不易,歡迎點贊收藏~`