A simple example on how to enable remote debugging using Delve for a Go application running in an Alpine Linux Docker container.
This example contains a simple Go web application which returns Hello world!
on all HTTP requests to the endpoint /hello
. The application is packaged into
a Docker image which includes the Delve debugger and can accept remote debugging
sessions on a user specified port.
Explore the code to see how this is accomplished :).
Build the application and Docker image. This example utilizes a multi-stage Docker build to download and install Delve, and compile the application:
$ docker build ./ -t debug-example:latest -f Dockerfile
[+] Building 9.5s (18/18) FINISHED
...
Run a container:
$ docker run \
--rm \
-p 8080:8080 \
-p 40000:40000 \
-e REMOTE_DEBUG_PORT=40000 \
-e REMOTE_DEBUG_PAUSE_ON_START=true \
debug-example:latest
Starting application with remote debugging on port 40000
Process execution will be paused until a debug session is attached
Executing command: /bin/dlv --listen=:40000 --headless=true --log --api-version=2 --accept-multiclient exec /bin/app --
API server listening at: [::]:40000
...
Once the container is running, you can establish a remote debugging session for
the application on port 40000
(feel free to change the port - there's nothing
special about 40000
, I just like that number). While you can always use the
Delve command line client
to debug, I recommend using your IDE for this:
Note that because we set REMOTE_DEBUG_PAUSE_ON_START
, the main
function will
not be executed until a debug session is connected. This is particularly useful
if you want to debug an application from its first line of execution, however if
you don't need that, feel free to omit that environment variable and the
application will start normally.
Finally, set some breakpoints and make a request:
$ curl http://localhost:8080/hello
Hello world!
The .run
directory contains a
run/debug configuration
which you use for this example.