Docker-java: Execute commands on a container and receive their outputs in java

Created on 20 Nov 2019  路  4Comments  路  Source: docker-java/docker-java

I have created a container with the following command:

DockerClient dockerClient = DockerClientBuilder.getInstance().build();
CreateContainerResponse container = dockerClient.createContainerCmd("ubuntu")
.withStdinOpen(true)
.withTty(true)
.exec();
dockerClient.startContainerCmd(container.getId()).exec();
($ docker run -it ubuntu)

I need a Java Code to run commands inside this container and get their outputs back in the Java Code.

Also if there is a manual/documentation with some examples, please provide a link for that.

typquestion

All 4 comments

Is there any update on this issue? I would like to be able to run a command like:
docker exec -it <container_id_or_name> echo "Hello from container!"

docker-java provides all necessary APIs to do so.

  1. create exec (with stdout/stderr attached)
  2. start exec

when you start it, you provide a callback and listen to the frames.

Keep in mind that docker-java is a low level wrapper for Docker's API and does not provide high level API.

There projects (like Testcontainers) that give you a higher level API. Here is an example from Testcontainers:
https://github.com/testcontainers/testcontainers-java/blob/2e9adb94ec09c074c43984e14e710daf9d1d6c20/core/src/main/java/org/testcontainers/containers/ExecInContainerPattern.java#L51

Thanks @bsideup . The example linked looks pretty complicated so I looked at Testcontainers instead.

As I was just trying to check logs relating to the docker RUN command I was able to use waitingFor functionality like this:

container = new GenericContainer<>("example:latest").withExposedPorts(9080).waitingFor(Wait.forLogMessage(".*Example message meaning container is ready.*\\n", 1));
container.start();

@JDUNNIN glad you found it useful :)

I will close this issue (although we haven't heard from the author yet) since it doesn't look like there is an issue in docker-java.

Was this page helpful?
0 / 5 - 0 ratings