go delve remote debugging does not work with docker "network_mode: host"

Hi I am trying to run remote debugging using dlv inside a docker container with VSCode. Problem starts when I specify docker-compose flag network_mode: host instead of the specific port (This is required due to use of MQTT). This causes VSCode to throw to the following error: "Failed to continue: "Error: connect ENCONNREFUSED ...""

.vscode/launch.json

{
"version": "0.2.0",
"configurations": [
    {
        "name": "Remote Docker",
        "type": "go",
        "request": "attach",
        "mode": "remote",
        "remotePath":"/go/src/work/cmd/mapper",
        "port": 2345,
        // "host": "127.0.0.1",
        "cwd": "${workspaceFolder}/src/cmd/mapper",
        "args": [],
        "trace" : "verbose",
        "env" : {}
    },
]
}

docker-compose.yml

version: "3.4"
services:
  golang:
    container_name: golang
    image: gotestdlv:latest
    privileged: true
    volumes:
      - ./src/:/go/src/work/
    network_mode: host
    # ports:
      # - 2345:2345 # debug port

There can be a multitude of reasons why it does not work for you. Among them are:

  • The host networking driver only works on Linux hosts, so if you use Docker for Mac, Docker for Windows or Docker Enterprise Edition it won't work.
  • The port 2345 might be already in use on your machine, and the delve process might not be able to bind it.
  • You might be using the wrong hostname when connecting to your session (your snippet shows 127.0.0.1 but it is commented out, and I don't know what IP it selects when one is not provided).

I am not sure why you are trying to use the host networking mode however, as it is normally useful for two main use-cases: it is more performant to use it when a docker container needs to bind a large range of ports (hundreds or thousands of ports), and can be convenient when running a Docker swarm as long as services do not have conflicting ports within the swarm.

It doesn't seem to me like any of those cases are related to the situation you describe, so even though that was not your original question, it is my recommendation that you look for other solutions to solve the problem which you attempted to solve by using host networking mode.