I have a node.js project using Docker that I am trying to debug in Visual Studio Code. I am able to debug the project if one node is deployed using docker-compose up
, but if I try to deploy multiple replicas using docker-compose up --scale node=3
I run into the following error:
Bind for 0.0.0.0:9229 failed: port is already allocated
This error is occurring since there are multiple nodes all trying to attach to port 9229. Is there any way to dynamically allocate a port range for debugging instead?
My docker-compose file:
version: '3'
services:
node:
env_file: .env
build:
context: .
dockerfile: Dockerfile
ports:
- "3000"
- "9229:9229"
restart: always
volumes:
- .:/home/node/app
- /home/node/app/node_modules
environment:
VIRTUAL_HOST: node.local
NODE_ENV: development
VIRTUAL_PORT: 3000
.vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Docker: Attach to Node",
"type": "node",
"request": "attach",
"restart": true,
"port": 9229,
"address": "0.0.0.0",
"localRoot": "${workspaceFolder}",
"remoteRoot": "/home/node/app",
"protocol": "inspector"
}
]
}
Snippet from package.json
{
"scripts": {
"start": "node src/index.js",
"dev": "nodemon --inspect=0.0.0.0:9229 -L src/index.js"
}
}
CodePudding user response:
One option is to treat port 9229
the same way you treat port 3000
:
version: '3'
services:
node:
env_file: .env
build:
context: .
dockerfile: Dockerfile
ports:
- "3000"
- "9229"
restart: always
volumes:
- .:/home/node/app
- /home/node/app/node_modules
environment:
VIRTUAL_HOST: node.local
NODE_ENV: development
VIRTUAL_PORT: 3000
When you don't specify a host port, Docker will select a random port on the host; you can see these in docker ps
:
CONTAINER ID ... STATUS PORTS NAMES
404f6b766136 ... Up 2 seconds 8080/tcp, 0.0.0.0:49163->3000/tcp, :::49163->3000/tcp, 0.0.0.0:49162->9229/tcp, :::49162->9229/tcp example_node_3
7e16271b1dea ... Up 2 seconds 8080/tcp, 0.0.0.0:49161->3000/tcp, :::49161->3000/tcp, 0.0.0.0:49160->9229/tcp, :::49160->9229/tcp example_node_2
1117a0762bdf ... Up 11 seconds 8080/tcp, 0.0.0.0:49159->3000/tcp, :::49159->3000/tcp, 0.0.0.0:49158->9229/tcp, :::49158->9229/tcp example_node_1
From the above docker ps
output, we can see that if we want to reach port 9229 on container example_node_1
, we need to use port 49158
. If we want example_node_2
, we need port 49160
, etc.
That may be all you need.