Debug in VSCode: Attach Debugger To Containers
We all need to debug node program from time to time. If you are using VSCode as your IDE, it’s pretty straightforward.
Debugging with local files is even more comfortable. However, when you need to debug node program in a container, there are a few caveats need to notice.
Let’s start with a few js lines and Dockerfiles. (You can also clone this repo).
Or, skip to TL; DR :)
Get Started
index.js
|
|
Dockerfile
|
|
Dockefile_node5
|
|
What you can see here, are two different versions of node. If you are going to debug with older node versions, you will have to change the protocol and the port.
The following launch.json
will let VSCode how to attach to the code in the container properly.
launch.json
|
|
Build images and run containers
Now we have 2 Dockerfiles with different node versions; we need to build these images before we can run it.
|
|
Let try node 12 first, copy the launch.json
above into your configuration. And set breaking point at line 5.
Then start the container:
|
|
And start debug session with the green arrow:
When the bottom bar turns to orange, then it’s successfully attached to the container.
A few seconds later, you will see that line 5 has been highlighted. Seems familiar right?
But do we need to make the program to wait for a while before we can attach them?
No, of course. That’s where another useful argument --inspect-brk
comes in. Let’s change the --inspect
to --inspect-brk
:
|
|
And start the session again:
The program now stopped at the very beginning. After VSCode attached to it, you can go to any point you want.
What if I am still using an older node version (<= 7.6)?
Then you need to have some configurations changed. Remember that the protocol and the port mentioned above? That’s what we need to modify.
|
|
Change the configuration:
Start the container:
|
|
Things to remember here:
- When you are debugging using the old protocol, you need to expose different port
5858
instead of9229
. - The argument is
--debug
(or--debug-brk
) instead of--inspect=0.0.0.0
(or--inspect-brk=0.0.0.0
).
Finally, let’s debug!
TL; DR
Run your container
Node version <= 7.6
|
|
Node version >= 7.7
|
|
launch.json
|
|