Debug NodeJS applications with Docker

Stefan Pöltl
5 min readFeb 22, 2021

You covered your codebase with unit tests but you’re still facing some weird bugs from time to time and don’t know how to find the issues in your web application, serverless endpoint or cron job script? This post will guide you through the pain of setting up debuggers in your IDE and describes how a debugger works in detail.

All the code used in this post can be found here: https://github.com/stefpe/node_debugging

What is debugging?

Debugging means to find a bug/anomaly in your code/program. Normally you can use a debugger to start your program in a monitoring mode to see what happens by stepping through the code line by line(Interactive debugging).

Which methods are common to find bugs:

  • print debugging (console API -> console.log(‘Hello’);)
  • Interactive debugging(step through debugging)
  • Remote debugging / Debug a remote application with a local debugger tool

In this post we will checkout the interactive debugger and actually its some kind of remote debugging, because we run apps in a container.

Debug Node scripts with the help of Google Chrome

Let’s start to debug a simple script file with the following content(test.js):

const fib = n => {
if (n > 1) {
return fib(n - 1) + fib(n - 2)
} else {
return n;
}
};

const result = fib(3);

const log = `my result is ${result}`;
console.log(log);

To enable a debugging process listening on port 9229 waiting for a client at a breakpoint(start of debugging in the program), we run this script in the terminal with Docker:

docker run --rm -it -v $PWD/script:/app -w /app -p 9229:9229 node:12-alpine node --inspect-brk=0.0.0.0:9229 test.js

Now open Google Chrome and browse chrome:://inspect and you will find the following target:

After clicking on inspect and F10 you should see the following output in an appearing popup:

--

--