Why can't I remote debug with Docker/VScode?

Viewed 770

I'm trying to remotely debug a Go app using Docker/VScode. My files look like:

  • 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
              }
        ]
    }

I can see docker logs for my app, I know it's listening on 2345. But for whatever reason, I can't seem to debug the app. The other issue I'm seeing is, I can't see any logs for trying to run the launch.json.

Edit: I'm running this on Mac OSX, using Docker Desktop.

1 Answers

Docker desktop for Mac runs docker inside a Virtual Machine.

Instead of trying to reach 127.0.0.1:2345, you should use your Virtual machine IP.

Related