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?

  • 1
    Step back. First of all, learn how to use the ProcessBuilder interface (see https://stackoverflow.com/questions/6856028/difference-between-processbuilder-and-runtime-exec) ... 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! – GhostCat May 10 '22 at 09: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. – XPModder May 10 '22 at 09:38
  • 1
    Using a [Docker SDK](https://docs.docker.com/engine/api/sdk/), like [docker-java](https://github.com/docker-java/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. – David Maze May 10 '22 at 09:59
  • Here is an example of how I did this in the past: https://github.com/jonckvanderkogel/elasticsearch-research/blob/master/src/main/java/com/example/elasticsearchresearch/configuration/support/ElasticSearchSetupRunner.java – Jonck van der Kogel May 10 '22 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. – dave_thompson_085 May 10 '22 at 10:55

0 Answers0