This is a quick guide on how to set up the debugger in VS code server-side for use with Node.js in a Docker container. I recently worked on a project which uses the Koa.js framework as the API. Whilst trying to set up the debugger with VS code, a google search led to several articles that had conflicting information about how to set it up and the port number to expose, or was overly verbose and complicated.
To keep things simple, I have split this into 3 steps.
1) Check version of Node.js on server
To do this with docker-compose set up, use the following, replace [api] with the name of your docker container.
docker-compose exec api node --version
Inspector Protocol (Node V7+, since Oct 2016)
Recent versions of Node.js now uses the inspector protocol. This is easier to set up and is the default setting for new Node.js applications, as most documentation will refer to this protocol. This means that:
--inspectflag is required when starting the node process.
- By default, the port 9229 is exposed, and is equivalent to
- The port can be changed, eg.
--inspect-brk:1234. Here, the ‘-brk’ flag adds a breakpoint on start.
Legacy Protocol (Node V6 and earlier)
Older versions of Node.js (prior to V7) uses the ‘Legacy Debugger’. The version of Node.js used on my project was 6.14. This means that:
--debugflag is required when starting the node process.
- By default, the port 5858 is exposed, and is equivalent to
- This port cannot be changed.
For more information goto:
2) Expose port in Node and Docker
In ‘package.json’, add
--inspect:9229 depending on Node version) when starting Node, so:
"dev": "nodemon index.js", becomes
"debug": "nodemon --debug:5858 index.js",
In ‘docker-compose.yml’, run the debug node command and expose the port. In my case:
command: yarn dev
command: yarn debug
3) Set launch configuration of Debugger
In ‘/.vscode/launch.json’, my launch configuration is:
"name": "Docker: Attach to Node",
The port and protocol needs to correspond to the version of Node used as determine above. For newer versions of Node:
"port": "9229" and
"protocol": "inspector" should be used.
“localRoot” and “remoteRoot” should be set to the folder corresponding to the entry point (eg. index.js) of your Node application in the local repository and the docker folder respectively.
4) Attach debugger and go!
In VS code, set your breakpoints and press F5 or click the green triangle button to start debugging! By default VS code comes with a debug panel to the left and debug console to the bottom, and a moveable debug toolbar. Mousing over a variable shows its values if it has any.
I hope this article has been useful, and thanks for reading my first tech blog!
You liked this article? You'd probably be a good match for our ever-growing tech team at Theodo.