How to Debug a Go Application Running in Docker

Debug Go in Docker by running the container with the dlv debugger in headless mode and connecting your IDE to the exposed port.

Debug a Go application in Docker by running the container with the dlv debugger attached via TCP and connecting your IDE to the exposed port.

  1. Build your binary with debug symbols by setting CGO_ENABLED=0 and GOOS=linux if cross-compiling, or simply run go build -gcflags="all=-N -l" -o main main.go inside the container to disable optimizations and inlining.
  2. Start the container with the dlv debugger listening on a specific port by running docker run -p 2345:2345 -v $(pwd):/app -w /app your-go-image dlv debug --headless --listen=:2345 --api-version=2 --accept-multiclient ./main.
  3. Connect your IDE (like VS Code or GoLand) to the debugger by configuring a launch configuration with host: "localhost" and port: 2345.
docker run -p 2345:2345 -v $(pwd):/app -w /app your-go-image dlv debug --headless --listen=:2345 --api-version=2 --accept-multiclient ./main