Let’s see how to debug a Node.js application running in a Docker container.
Traditionally, debugging a Node.js application has been quite simple. When the runtime environment is local, you can run the application with one of Node.js’s flags to activate inspection mode and then connect a debugger, such as Chrome DevTools or VSCode.
However, when the application is running in a Docker container, things get more complicated. You’ll need to expose the container’s debugging port and establish a connection to it.
The first step is to add the appropriate flag that enables inspection mode when starting the application process. There are two main flags available:
- –inspect: Enables inspection mode and exposes the debugger on port 9229.
- –inspect-brk: Enables inspection mode, exposes the debugger on port 9229, and pauses the process execution until a debugger is connected.
The most common flag to use is --inspect
. Additionally, you can specify the address on which the connections will be listened. By default, it’s 127.0.0.1. However, in our case, we want to allow external connections, so we’ll use 0.0.0.0
. More information can be found in the official documentation.
{
"scripts": {
"start": "node --inspect=0.0.0.0 index.js"
}
}
On the other hand, to access the debugger from outside the container, it is essential to expose port 9229. If you are using Docker Compose, this can be done by specifying the port in the service configuration, like this:
services:
app:
ports:
- 9229:9229
If you’re using a Dockerfile, you can expose the debugger’s port by specifying it with the EXPOSE instruction. For example:
EXPOSE 9229
This declares that port 9229 is used by the container, allowing it to be made accessible when running the container with the appropriate port mapping (e.g., -p 9229:9229 when using docker run).
Then, you can connect to the debugger using your preferred tool. For example, if you’re using Chrome DevTools, you can visit chrome://inspect
and see the list of available targets.