1

I hava Java project and I want to execute docker command from my code. Command:

docker run --rm -v "$(pwd)":/browsertime sitespeedio/browsertime:16.3.0 --video --visualMetrics https://www.sitespeed.io/

I have tried to write Java class with following code inside main-method:

Runtime.getRuntime().exec("docker run --rm -v \"$(pwd)\":/browsertime sitespeedio/browsertime:16.3.0 --video --visualMetrics https://www.sitespeed.io/");

This has compiled fine and got the result in console "Process finished with exit code 0", so everything has been okey, but no result had been got (that command had to create folders and files and so on...).

So how should I run that docker command? If you have answer using DockerClient (not directly using Runtime.getRuntime().exec) - then go here: How can I execute predefined docker command from Java application with DockerClient?

5
  • 1
    Step back. First of all, learn how to use the ProcessBuilder interface (see stackoverflow.com/questions/6856028/…) ... then understand: your initial command line is ran by a SHELL. Therefore things like env wars like $(pwd) work. There is no magic that fills up that $(pwd) when you send a command string within java. YOUR code has to make sure that the correct path information is already in that string that you "send down" to be executed! Commented May 10, 2022 at 9:31
  • Also make sure the java program doing this has the neccessary privileges to create/modify the files and folders. The command will inherit the same privileges that the java program has. Commented May 10, 2022 at 9:38
  • 1
    Using a Docker SDK, like docker-java, will probably be easier and safer than trying to run a docker shell command. But do remember that the ability to launch a Docker container at all comes with the power to root the entire host, and that this approach won't necessarily be portable to other container runtimes. Commented May 10, 2022 at 9:59
  • Here is an example of how I did this in the past: github.com/jonckvanderkogel/elasticsearch-research/blob/master/… Commented May 10, 2022 at 10:43
  • 1
    @GhostCat+ actually $(pwd) is command substitution; variable expansion is ${PWD} or $PWD (and it can be either a shell variable or an environmental variable). But the main point is correct that both of these (and more) work only in shell not java. Commented May 10, 2022 at 10:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.