How to debug a Go program running on a remote server?

To debug a Go program running on a remote server, you can follow these steps:

  1. Start the remote program with debugging support:

    • Add the -gcflags="all=-N -l" flag to disable compiler optimizations, allowing easier debugging. For example: go run -gcflags="all=-N -l" main.go.
    • Alternatively, you can build the program with debugging support and then run it: go build -gcflags="all=-N -l" main.go, followed by executing the binary remotely.
  2. Enable the server to listen for remote debugging connections:

    • Set the environment variable GODEBUG with the value gctrace=1. For example: export GODEBUG=gctrace=1.
    • Set the GOTRACEBACK environment variable to crash to get detailed information on a crash. For example: export GOTRACEBACK=crash.
  3. Configure the server to listen for remote debugging connections:

    • Start the program with the -debug=:2345 flag, specifying the port number where you want the debugger to listen. For example: go run -gcflags="all=-N -l" -debug=:2345 main.go.
  4. Make sure the server is accessible from your local machine:

    • Ensure that the necessary ports (e.g., 2345) are open on the remote server's firewall to allow incoming connections.
    • Note the IP address or domain name of the remote server.
  5. Install a debugger:

    • Install a Go debugger on your local machine. Popular options include Delve and GoLand.
  6. Connect the debugger to the remote server:

    • Use the debugger's configuration settings to connect to the remote debugging server.
    • Provide the IP address or domain name of the remote server and the port number you specified in step 3.
  7. Set breakpoints and start debugging:

    • Once connected, set breakpoints in your code where you want to inspect and analyze its behavior.
    • Start the debugger and execute the remote program.
    • The debugger will break at the specified breakpoints, allowing you to examine variables, inspect the call stack, and step through the code.

By following these steps, you can effectively debug a Go program running on a remote server using a debugger from your local machine.