如何使用VSCode在Docker中调试Golang应用程序?

3

我正在学习在Docker中调试Golang应用程序。我在shell中使用dlv connect命令已经成功连接。我可以添加断点、继续执行和执行下一步操作...但是在VSCode中却无法做任何事情,只能等待halting

我点击主函数左侧的红点,然后点击类似“播放”按钮的绿色按钮。容器中的程序运行了,但无法在主函数上停止。

我是否以错误的方式使用了VSCode?我需要你的帮助。谢谢。

这是我的delve镜像:

#Dockerfile
FROM supinf/go:1.8-builder

RUN apk --no-cache add tini \
&& apk --no-cache add --virtual build-dependencies git \

# Compile delve
&& go get github.com/derekparker/delve/cmd/dlv \
&& cd $GOPATH/src/github.com/derekparker/delve \
&& go install github.com/derekparker/delve/cmd/dlv \

# Clean up
&& apk del --purge -r build-dependencies \
&& rm -rf /go/src/*

ENTRYPOINT ["/sbin/tini", "--"]
CMD ["dlv", "-h"]

docker build -t mydelve .

这是我的 Golang 代码:

package main

import (
    "fmt"
    "sync"
    "time"
)

func dostuff(wg *sync.WaitGroup, i int) {
    fmt.Printf("goroutine id %d\n", i)
    time.Sleep(60 * time.Second)
    fmt.Printf("end goroutine id %d\n", i)
    wg.Done()
}

func main() {
    var wg sync.WaitGroup
    workers := 10

    wg.Add(workers)
    for i := 0; i < workers; i++ {
            go dostuff(&wg, i)
    }
    wg.Wait()
}

以下是运行容器的命令:

docker run --rm -p 2345:2345 
           -v $GOPATH/src:/go/src 
           -w /go/src/test/dlv 
           --security-opt seccomp=unconfined 
           mydelve 
               dlv debug --headless --listen=:2345 --log`

连接容器

dlv connect 127.0.0.1:2345 --wd . --log

操作成功。

使用VSCode

launch.json

{
    "version": "0.2.0",
    "configurations": [
       {
            "name": "Remote",
            "type": "go",
            "request": "launch",
            "mode": "remote",
            "program": "${fileDirname}",
            "port": 2345,
            "host": "127.0.0.1",
            "env": {},
            "args": []
        }
    ]
}

容器中的日志

$ docker run --rm -p 2345:2345 -v $GOPATH/src:/go/src -w /go/src/test/dlv --security-opt seccomp=unconfined mydelve dlv debug --headless --listen=:2345 --log
2017/05/22 09:07:56 server.go:73: Using API v1
2017/05/22 09:07:56 debugger.go:97: launching process with args: [/go/src/test/dlv/debug]
API server listening at: [::]:2345
2017/05/22 09:08:00 debugger.go:505: continuing
goroutine id 3
goroutine id 9
goroutine id 4
goroutine id 5
goroutine id 6
goroutine id 7
goroutine id 8
goroutine id 1
goroutine id 0
goroutine id 2
end goroutine id 6
end goroutine id 3
end goroutine id 9
end goroutine id 4
end goroutine id 5
end goroutine id 8
end goroutine id 7
end goroutine id 1
end goroutine id 0
end goroutine id 2
2017/05/22 09:08:10 debugger.go:496: halting
1个回答

0
我认为你需要修复的主要问题是将主机从“127.0.0.1”(本地主机)更改为容器的 IP(在你的 launch.json 文件的第 11 行)。这里有一篇可能会有所帮助的文章:

https://blog.intelligentbee.com/2016/12/15/debugging-golang-apps-in-docker-with-visual-studio-code/

根据这个,"你可能需要将主机IP更改为docker-machine IP输出的内容。" 或者,如果您正在使用kubernetes,则可能需要使用"kubectl describe pod ",然后查找"IP:"

如果端口已经暴露并映射,可以通过 localhost:<exposed-port> 访问它,不需要指向容器 IP,因为每次启动容器时 IP 都会改变。 - Daniel Andrei Mincă

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接