登录
首页 >  Golang >  Go问答

为什么无法使用 Docker/VScode 进行远程调试?

来源:stackoverflow

时间:2024-03-30 08:12:32 429浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《为什么无法使用 Docker/VScode 进行远程调试?》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我正在尝试使用 docker/vscode 远程调试 go 应用程序。我的文件如下所示:

  • main.go
package main

    import (
        "log"
        "net"
        "net/http"
        "strings"
    )
    
    func main() {
        http.handlefunc("/", func(w http.responsewriter, r *http.request) {
            message := r.url.path
            message = strings.trimprefix(message, "/")
            message = "hello, " + message + "!"
    
            w.write([]byte(message))
        })
    
        log.print("starting web server")
        listener, err := net.listen("tcp", ":8080")
        if err != nil {
            log.fatal(err)
        }
    
        log.printf("start listening: %v", listener.addr().string())
    
        if err := http.serve(listener, nil); err != nil {
            log.fatal(err)
        }
    }
  • dockerfile
from golang:1.12
    
    env gopath /go
    env path $gopath/bin:/usr/local/go/bin:$path
    
    run go get github.com/go-delve/delve/cmd/dlv
    
    # set the working directory to /go/src
    workdir $gopath/src
    
    # copy everything from the current directory to the working directory inside the container
    # (as set by workdir)
    copy . .
    
    # 8080 is for the web application
    expose 8080 2345
  • docker-compose.yml
version: "3.0"
    
    services:
      web:
        container_name: go-delve-docker-vscode-example
        build: "./"
        ports:
          - "8080:8080"
          - "2345:2345"
        security_opt:
          - "seccomp:unconfined"
        tty: true
        stdin_open: true
        # command: go run main.go
        command: dlv debug --headless --listen=:2345 --api-version=2 --log main.go
  • launch.json
{
        "version": "0.2.0",
        "configurations": [
              {
                    "name": "Delve into Docker",
                    "type": "go",
                    "request": "launch",
                    "mode": "remote",
                    "remotePath": "/go/src/",
                    "port": 2345,
                    "host": "127.0.0.1",
                    "program": "${workspaceRoot}",
                    "showLog": true
              }
        ]
    }

我可以看到我的应用程序的 docker 日志,我知道它正在监听 2345。但无论出于何种原因,我似乎无法调试该应用程序。我看到的另一个问题是,我看不到任何尝试运行 launch.json 的日志。

编辑:我在 mac osx 上使用 docker desktop 运行此程序。


解决方案


适用于 Mac 的 Docker 桌面在虚拟机内运行 docker。

您应该使用虚拟机 IP,而不是尝试访问 127.0.0.1:2345。

今天关于《为什么无法使用 Docker/VScode 进行远程调试?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>