Tom Eijkelenkamp
Tom Eijkelenkamp

Reputation: 31

Run a docker container from inside java program

I try to run a docker container from inside a java program, but the docker container won't run.

When I execute this command I use for the process builder in the terminal the container starts and everything works.

I printed the working directory inside the java program and this is the right directory to start the docker container.

I also changed the command to:

String[] dockerCommand = new String[] {"java", "-cp", "target/MavenAsteroidsServer-1.0-SNAPSHOT.jar", "asteroidsserver.AsteroidsServer", "1600", "1600", "127.0.1.1", "8851", "8901"};

This worked, so running the program without a docker container works.

This is the code I used to run the docker container from inside the java program:

String[] dockerCommand = new String[] {"docker", "run", "-it", "--rm", "--net=\"host\"", "-p", "8901:8901", "-v", "\"$PWD\":/app", "-w", "/app", "demo/maven:3.3-jdk-8", "java", "-cp", "target/MavenAsteroidsServer-1.0-SNAPSHOT.jar", "asteroidsserver.AsteroidsServer", "1600", "1600", "127.0.1.1", "8851", "8901"};

ProcessBuilder probuilder = new ProcessBuilder(dockerCommand);

Process process;
try {
    process = probuilder.start();
    int status = process.waitFor();
} catch (InterruptedException e) {
} catch (IOException ex) {
}

I want the container to run, but nothing happens. Also, I get no error messages when I try to catch them in the try and catch block (not shown in the code)

Upvotes: 3

Views: 1327

Answers (1)

David Maze
David Maze

Reputation: 159081

Most ways to programmatically run commands from programs don't involve a shell and so don't do any of the nice things that shells do like, for example, variable interpolation. In particular, this pair of arguments:

..., "-v", "\"$PWD\":/app", ...

tells Docker (I think) to create a new named volume named "$PWD" (as in quote, dollars, P, W, D, quote), and mount the new empty volume on /app in the container. Nothing would cause this to get expanded to the name of the current directory or remove the extra quotes.

Upvotes: 1

Related Questions