Debugging Node.js in a Docker container
First, we’ll need to create a Dockerfile,
FROM node
COPY package.json package.json
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "."]
and a docker-compose.yaml
version: '3.6'
services:
app:
build: .
ports:
- "3000:3000"
Now if you run docker-compose up
, you’ll be able to reach your service on http://localhost:3000
.
The next step is to expose the debug port to the outside world. First, let’s create a debug-compose.yaml
.
version: '3.6'
services:
app:
build: .
ports:
- "3000:3000"
- "9229:9229"
command:
- node
- "--inspect-brk=0.0.0.0"
- "."
As you can see, we opened up port 9229
, which is the debug port of Node.js apps.
We also overrode the command we specified in the Dockerfile.
The --inspect-brk=0.0.0.0
argument does two different things:
--inspect
tells Node that we want to run our app in debug mode.- by adding
-brk
we also make sure that the app stops at the first line, so we have enough time to open up the inspector adding=0.0.0.0
opens up the debugger to connections from any IP.
By default, the inspector is bound to 127.0.0.1
.
Which makes sense, as we usually don’t want to allow people from all around the world to attach a debugger to our app.
However, the container is a different host with a different IP than our host machine, so we won’t be able to reach it. It is fine as long as we do it locally; however, we don’t want to run it on a live server like this.
For this reason make sure it is a different file from your docker-compose.yaml
.
With a bit more work, you can expose the debug port from your staging cluster to your IP But in that case, to your IP only — and debug issues there as well.
- Also, note that the port forwarding rules are enclosed in
-s
. - If you omit the quotes the rule might not work.
- It will be difficult to figure out why you’re unable to attach the debugger to your process.
- With all that said, you should be able to inspect your app in the dev tools.