Docker+Traefik环境下Node TS应用VS Code调试连接失败求助
The ECONNREFUSED error occurs because your Node app's debug port (9229) wasn't properly exposed to your host machine, and the existing port mapping in your docker-compose file pointed to Traefik instead of your core service. Here's how to resolve this step-by-step:
Step 1: Correct Docker Compose Port Mapping
Update your docker-compose.yml to map the host's 9229 port to your core service's debug port, and remove the unnecessary Traefik port mapping:
version: '3' services: traefik: image: traefik:1.7 command: --docker --docker.exposedbydefault=false ports: - '80:80' # Remove the 9229:9229 line here volumes: - /var/run/docker.sock:/var/run/docker.sock core: image: node:alpine labels: - traefik.enable=true - traefik.port=4001 - traefik.backend=core - traefik.frontend.rule=Host:core.localhost volumes: - ./leav_core:/app working_dir: /app command: [sh, -c, 'npm start'] expose: - '9229' ports: - "9229:9229" # Add this line to map host port 9229 to container's 9229 volumes: arango_data: driver: local
Why this change?
- The original
9229:9229entry in Traefik's ports was forwarding your host's port 9229 to Traefik (which doesn't use this port for debugging), not your Node app. - Adding
ports: - "9229:9229"to the core service exposes the container's debug port directly to your host, allowing VS Code to connect to it.
Step 2: Update VS Code Debug Configuration
Refine your .vscode/launch.json to clarify connection details and improve path mapping:
{ "version": "0.2.0", "configurations": [ { "name": "Docker: Attach to Node", "type": "node", "request": "attach", "port": 9229, "address": "localhost", "remoteRoot": "/app", "localRoot": "${workspaceFolder}/leav_core", // Maps local code to remote container path "skipFiles": [ "<node_internals>/**" // Skips Node.js internal files during debugging ] } ] }
Key improvements:
localRootensures VS Code correctly maps your localleav_coredirectory to the/appdirectory in the container, so breakpoints work as expected.- Explicit
portandaddressremove ambiguity about where the debugger should connect.
Step 3: (Optional) Pause App for Debugger Attachment
If your app starts too quickly before the debugger can attach, modify your npm start command to use --inspect-brk instead of --inspect:
// In your package.json "scripts": { "start": "ts-node --inspect-brk=0.0.0.0:9229 --type-check src/" }
This will pause the app immediately after starting, waiting for the debugger to connect before executing any code.
Step 4: Restart Containers and Attach Debugger
- Stop your running containers:
docker-compose down - Start them again:
docker-compose up -d - In VS Code, select the "Docker: Attach to Node" configuration and click the debug play button.
You should now be able to set breakpoints and debug your Node app running in Docker, while still accessing it via http://core.localhost through Traefik.
内容的提问来源于stack exchange,提问作者Tdy

