My question is, if I can run Java and Debug it from within Visual Studio Code. I can edit my code and then start it in a container. But is it also possible to run the docker container, having a volume with the code folder mounted into the container and then configure Visual Studio Code somehow to use Java from the container? I saw there is the .vscode folder with launch.json or settings.json, but I found no way so far to use the run/debug command and use Java from within the Docker container. I was looking for a way to use java 11 without breaking my current config.
3 Answers
Your best option really is to use the Remote Development extension pack for Visual Studio Code, and then use Docker containers.
See this sample for details.
Comments
You can use any IDE with java remote debugging. The only thing you need from a container is the java runtime, so you can map working directory to container and run your current jar from there.
The command I use in a Makefile
// ... you can also build your image in the same makefile
// have to recompile on changes to keep mappings accurate
compile_local:
mvn package -P debug -DskipTests
// find the jar to be used as launch target
WW_COMPILED_JAR = $(shell find target/my-jar-*.jar | sort -r | head -n 1)
start_remote_debugger_local: compile_local
docker run \
// if you have some .env to pass (optional)
--env-file .env \
// java debugger config to wait for debugger to attach on launch
-e JAVA_TOOL_OPTIONS="-agentlib:jdwp=transport=dt_socket,address=*:5005,server=y,suspend=y" \
// map debugger port
-p 5005:5005 \
// command to run jar
--entrypoint="java" \
// map local dir to any dir inside a counter
-v $(shell pwd):/var/debug_mount \
--workdir="/var/debug_mount" \
// name of your image
my-java-image-name \
// arguments to java command
-cp /var/debug_mount/$(WW_COMPILED_JAR) MyEntrypointClass
run container via
make start_remote_debugger_local
And attach using the following launch config
{
"type": "java",
"name": "Attach To My App (Docker)",
"request": "attach",
"hostName": "127.0.0.1",
"port": 5005,
"sourcePaths": [
"${workspaceFolder}/src"
]
}
You also can use a shell script or anything else instead of Makefile to run the container with such a config (or even make it a task in tasks.json and make attach launch json entry depend on it).
You can also choose to rebuild image from scratch instead of mapping to local directory.