How can I attach VS Code to a node process running in a docker container

谁都会走 提交于 2020-01-13 09:12:18

问题


I'm trying to attach the Visual Studio Code debugger to a node.js app that is running inside a Docker container.

I start the app like:

node --debug-brk app.js

I expose the debugger port in docker-compose.yml:

app:
  build: .
  working_dir: /code
  volumes:
    - .:/code
  command: npm run debug
  ports:
    - "3004:3000"
    - "5858:5858"

My launch.json looks like:

{
    "version": "0.1.0",
    "configurations": [
        {
            "name": "Attach",
            "type": "node",
            "address": "localhost",
            "port": 5858
        }
    ]
}

Now, when I start the application and attach the debugger this will correctly connect (I can see the values flashing in the debugger UI already), but then it will stop, telling me the following:

Error opening 'app.js' (File not found: /code/app.js).

This is due to the fact that docker will not mount the app in root but in /code (see volumes in docker-compose.yml) and VS code is confused by the sudden offset.

When I run the application outside the container (i.e. locally, without offset) it works just as expected and I can use the debugger as expected.

There seems to be a cwd option for the launch configuration but I am not sure if that makes any difference in my case.

Can I fix this path offset? Am I missing something else here?


回答1:


This feature is now officially supported by VSCode: https://github.com/Microsoft/vscode-node-debug/issues/8




回答2:


I think your debugger is being tricked because your app path inside docker is /code and on your computer it is something different.

Maybe something like /home/m90/code.

So when your debugger tries to look at your code on your local machine. It looks at /code which exists only inside of docker. This path makes no sense outside of docker.

If you could tell your debugger to look for you code at the correct place on your machine (again outside of the docker container) that would fixed it.

Another way would be to have the same path for your code inside and outside of docker.




回答3:


Try this modified version of docker-compose.yml. (with copy /code directory in docker to your host directory /code)

docker-compose.yml

app:
  build: .
  working_dir: /code
  volumes:
    - /code:/code
  command: npm run debug
  ports:
    - "3004:3000"
    - "5858:5858"

only changed one line: /code:/code instead of .:/code




回答4:


You could try bind-mounting your current directory on /code so that VS can find your source code there: sudo mount --bind . /code




回答5:


For me it didn't work until I used inspect: node --inspect=5858 app.js



来源:https://stackoverflow.com/questions/33032164/how-can-i-attach-vs-code-to-a-node-process-running-in-a-docker-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!