Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tangoabcdelta/fe0dc34a71415afbe80251cb96bbaba9 to your computer and use it in GitHub Desktop.
Save tangoabcdelta/fe0dc34a71415afbe80251cb96bbaba9 to your computer and use it in GitHub Desktop.
How to Debug a Node.js app in a Docker Container

Source: https://blog.risingstack.com/how-to-debug-a-node-js-app-in-a-docker-container/#debuggingnodejsinadockercontainer

Debugging Node.js in a Docker container

1

First, we’ll need to create a Dockerfile,

FROM node

COPY package.json package.json  
RUN npm install

COPY . .  

EXPOSE 3000
CMD ["node", "."]

2

and a docker-compose.yaml

version: '3.6'

services:
  app: 
    build: .
    ports:
      - "3000:3000" 

3

Now if you run docker-compose up, you’ll be able to reach your service on http://localhost:3000.

4

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

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.

Debugger Binding

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment