How to get output of docker executed command in docker-java library

197 Views Asked by At

I am trying to pull an alpine image using docker-java library. Image got pulled successfully but I am not seeing any docker output on console. How to enable logging in docker-java library.

public class DockerPull {
   
    public static void main(String[] args) throws InterruptedException {
        DockerClientConfig standard = DefaultDockerClientConfig.createDefaultConfigBuilder().build();

        DockerClient dockerClient = DockerClientBuilder.getInstance(standard).build();

        dockerClient.pullImageCmd("alpine:latest").exec(new PullImageResultCallback()).awaitCompletion(3600, TimeUnit.SECONDS);
    }
}

Output: Process finished with exit code 0

1

There are 1 best solutions below

0
On

Check https://github.com/docker-java/docker-java/issues/738

This is some code I've made:

public class DockerizedServerInstantiator {
public static class StdioAdapter extends ResultCallback.Adapter<Frame> {

        @Override
        public void onNext(Frame object) {
            this.onLineGot(new String(object.getPayload()), object.getStreamType().equals(StreamType.STDERR));
        }

        private void onLineGot(String line, boolean stderr) {
            System.out.println((stderr ? "(err) " : "") + line);
        }
}

/**
 * Attaches Docker output to a callback method
 * @param dockerClient Docker client
 * @param container Container to attach
 * @param callback Object with the callback method to call
 */
private static void attachStdio(DockerClient dockerClient, CreateContainerResponse container, ResultCallback<Frame> callback) {
        dockerClient.logContainerCmd(container.getId())
                .withStdOut(true)
                .withStdErr(true)
                .withFollowStream(true)
                .exec(callback);
}

public void startDocker() {
        DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().build();
        final DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();

        CreateContainerResponse container;
        StartContainerCmd cnt;
        container = dockerClient.createContainerCmd(...)
                    .withCmd(...).exec();
        cnt = dockerClient.startContainerCmd(container.getId());
        cnt.exec();

        attachStdio(dockerClient, container, new StdioAdapter());
}
}