how to execute docker commands through Java program
Asked Answered
O

3

8

Instead of calling Docker remote APIs, I need develop a program which just talks to Docker Linux Client (not Docker daemon). Here is my code

    try {
        String[] command = {"docker", "run", "-it", "tomcat:9", "bash"};
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.inheritIO();
        Process proc = pb.start();

        InputStream is = proc.getInputStream();
        OutputStream os = proc.getOutputStream();

        BufferedReader reader
                = new BufferedReader(new InputStreamReader(is));

        BufferedWriter writer
                = new BufferedWriter(new OutputStreamWriter(os));
        writer.write("pwd");
        writer.flush();
        String line = "";
        while ((line = reader.readLine()) != null) {
            System.out.print(line + "\n");
        }

        proc.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    }

I always get errors. If I use "-it", it will says "cannot enable tty mode on non tty input", if I use "-i", I will get a Stream Closed Exception.

Is there any way to solve this problem?

Oxford answered 14/6, 2016 at 11:0 Comment(1)
You should use the docker remote API and use it to create/start a container. See docs.docker.com/engine/reference/api/docker_remote_api.Ahmadahmar
C
4

To overcome the error you're facing, you should use "-i" instead of "-it". The -t arg tells docker to allocate a pseudo tty.

Having said that, I agree with Florian, you should use the docker remote api. https://docs.docker.com/engine/reference/api/docker_remote_api/

Copeck answered 14/6, 2016 at 11:24 Comment(2)
By using docker remote api, I need to develop a parser to parse Docker Commands to get the command type and parameters. I just wanna users to type Docker Commands directly in my application.Oxford
Fair enough, if you want people to type docker commands into your app.Copeck
T
3

You can use docker client for java (e.g. https://github.com/spotify/docker-client). Here is example of usage:

public void startContainer(String containerId) throws Exception {
    final DockerClient docker = DefaultDockerClient.builder()
            .uri(URI.create("https://192.168.64.3:2376"))
            .dockerCertificates(new DockerCertificates(Paths.get("/Users/d.romashov/.docker/machine/machines/dinghy")))
            .build();

    docker.startContainer(containerId);
}
Turnaround answered 13/12, 2017 at 14:14 Comment(0)
D
0

I will suggest you, don't use any input or output stream, instead, write the output in a file in the docker image. And read your file in your java main Program.

Hope this helps

Danitadaniyal answered 11/1, 2018 at 10:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.