Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to execute docker commands through Java program

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?

like image 872
Chris Tien Avatar asked Jun 14 '16 11:06

Chris Tien


People also ask

Can you use docker with Java?

You can use Docker to run a Java application in a container with a specific runtime environment. This tutorial describes how to create a Dockerfile for running a simple Java application in a container with OpenJDK 17. It also shows how to create a Docker image with your application to share it with others.

How do I run a command docker?

Running Commands in an Alternate Directory in a Docker Container. To run a command in a certain directory of your container, use the --workdir flag to specify the directory: docker exec --workdir /tmp container-name pwd.

Does docker need Java running?

If you prefer to not install Java on your machine, you can skip this step, and continue straight to the next section, in which we explain how to build and run the application in Docker, which does not require you to have Java installed on your machine. Let's start our application and make sure it is running properly.

Why docker is used in Java?

Docker makes it easier to provide a consistent development environment for your whole team, particularly when your team must frequently shift from one environment to another. Your team can easily use the same OS, the same language run-time environment, and the same system libraries regardless of the host OS.


1 Answers

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/

like image 62
CamW Avatar answered Oct 13 '22 13:10

CamW