How To Debug Nodejs in Docker
I know what crossed your mind straight away: why would you debug Nodejs in Docker ?!? :)
There should indeed be no need to debug an app in Docker. In a perfect world, it should be done in the development environment with your favourite IDE…
But, the world is not perfect, and there will always be some environment-related issues that will require you to tackle the issue on the spot.
Let us take an example of running a Nodejs app inside of Docker container with node-rest-API id.
First, we will need to enter into the container with the following command:
docker exec -i node-rest-API /bin/sh
The command above will get us into the containers shell command line, and here we should be able to navigate to Nodejs script (based on your WORKDIR
specified in Dockerfile).
By default, Nodejs has a debugger built into the runtime environment. You can read more about it here.
In short, to use it, we need to start the server with the inspect
flag.
E.g.: node inspect <node script> # you can obtain the path to the node script from Dockerfile/WORKDIR
.
Since there is already a server running in the container we will have to stop the current Nodejs server:
ps aux | grep node # to obtain the process ID
kill <process ID>
Once the server restarted with the 'inspect' flag, it will open the debugger console at the first line of the server script, and we can start debugging the application.
It might be pretty hard to find the bug from the first line of code, that's why node has a debugger
statement.
And if we want to stop at a particular line, we need to add a debugger
statement to the script.
You will have to modify the Nodejs script in Docker container or rebuild and redeploy the new source code with the debugger
statements inside. Depends on your project and use case.
E.g.
for (const key in stats) {
debugger;
if (Object.prototype.hasOwnProperty.call(stats, key)) {
const value = stats[key];
...
}
}
When we are in a position to start debugging, we can use the following commands to move around the code:
- cont, c: Continue execution
- next, n: Step next
- step, s: Step in
- out, o: Step out
- pause: Pause running code (like a pause button in Developer Tools)
And once we are at the variable we want to inspect we can do so inside of repl
terminal (just type repl
in the debugger console and name of the variable):
That is it. Hope it helps and clap if it does ;)