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.
- Build your binary with debug symbols by setting
CGO_ENABLED=0andGOOS=linuxif cross-compiling, or simply rungo build -gcflags="all=-N -l" -o main main.goinside the container to disable optimizations and inlining. - Start the container with the
dlvdebugger listening on a specific port by runningdocker run -p 2345:2345 -v $(pwd):/app -w /app your-go-image dlv debug --headless --listen=:2345 --api-version=2 --accept-multiclient ./main. - Connect your IDE (like VS Code or GoLand) to the debugger by configuring a launch configuration with
host: "localhost"andport: 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