SoFunction
Updated on 2025-04-07

Detailed tutorial on operating Docker using Java backend

1. Why do you need to use a backend program to operate Docker

Docker is an integral part of modern development and deployment processes. It simplifies the environment configuration, packaging, and distribution of applications, making it easier and more consistent to run the same application on different machines. This article will explain in detail how to use the command line tool (CMD) to manipulate Docker to configure the environment.

Implementing back-end operation docker can be used to implement cloud IDE, one-click environment construction, multi-person collaboration environment, interactive programming teaching, visual deployment and management and other functions. It is the only way for Docker to move from a server to a client.

2. Install Docker

1. Install Docker

I've written a detailed blog, please move:The basic concepts of Docker, installation steps and some simple usages_docker_me

2. Start Docker

After the installation is complete, start Docker Desktop and make sure it works properly. You can verify it in CMD with the following command:

docker --version

3. Use Java backend to operate docker

1. Build a docker image and generate a container

The purpose of this step is to generate new images and containers through Docker based on DockerFlie files, code, and other configuration data files in the local directory.

A simple DockerFile example:

# Use the official Python runtime as parent imageFROM python:3.8-slim
 
# Set up the working directoryWORKDIR /app
 
# Copy the current directory contents into the container located in /appCOPY . /app
 
# Any required packages specified in the installationRUN pip install --no-cache-dir -r 
 
# Make port 80 available for use outside this containerEXPOSE 80
 
# Define environment variablesENV NAME World
 
# Run when the container startsCMD ["python", ""]

Among them, 0419test is the tag name for the image to be built.

Pay attention to modifying the working directory and change it to your actual folder directory.

    public void buildImageAndContainer(){
        try {
            // Set the first command: build the Docker image            ProcessBuilder buildProcessBuilder = new ProcessBuilder("docker", "build", "-t", "test0419", ".");
 
            // Set the working directory to "E:\\code\\docker\\test"            (new File("E:\\code\\docker\\test"));
 
            // Start the command to build the image and wait for it to complete            Process buildProcess = ();
            ();
 
            // Read and print out the output of the image to build            printProcessOutput(buildProcess);
 
            // Check whether the build is successful            if (() == 0) {
                // Set the second command: Run the Docker container                ProcessBuilder runProcessBuilder = new ProcessBuilder("docker", "run", "-v", "E:/code/docker/test:/app", "-p", "80:80", "test0419");
 
                // Start the command to run the container                Process runProcess = ();
 
                // Read and print out the output of the running container                printProcessOutput(runProcess);
 
                // You can wait here for the process running in the container to end, or perform other operations as needed                // ();
            } else {
                ("Docker image build failed.");
            }
        } catch (IOException | InterruptedException e) {
            (e);
            ();
        }
    }
 
    // Private method for outputting print content    private static String printProcessOutput(Process process) throws IOException {
        String output;
        String errorInfo;
        // Read and print standard output        output = readAndPrint((), "");
        // Read and print standard errors        errorInfo = readAndPrint((), "");
        return output+errorInfo;
    }
    private static String readAndPrint(InputStream inputStream, String prefix) throws IOException {
        StringBuilder output = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while ((line = ()) != null) {
                (prefix).append(line).append(());
                (prefix + line); // Print to the console at the same time            }
        }
        return ();
    }

2. Delete containers and mirrors after execution

Delete containers and images, free resources, and usually run after the container has executed the code.

    // Delete containers and images    public String deleteContainerAndImage(String imageName){
        // Define a thread pool for deletion        ExecutorService executorService = (2);
 
        // Asynchronously get the container ID list and delete the container        (() -> {
            try {
                List<String> containerIds = new ArrayList<>();
                String command = "docker ps -a -q --filter ancestor=" + imageName;
                ProcessBuilder processBuilder = new ProcessBuilder((" "));
                Process process = ();
 
                BufferedReader reader = new BufferedReader(new InputStreamReader(()));
                String line;
                while ((line = ()) != null) {
                    (());
                }
 
                int exitCode = ();
                if (exitCode != 0) {
                    ("Command executed with error. Exit code: " + exitCode);
                    return ;
                }
 
                // Delete the container                for (String containerId : containerIds) {
                    String deleteContainerCommand = "docker rm -f " + containerId;
                    executeCommand(deleteContainerCommand);
                }
 
            } catch (IOException | InterruptedException e) {
                ();
            }
        });
 
        // Asynchronously delete the mirror        (() -> {
            // Wait for the container to be deleted            try {
                (5); // Wait for 5 seconds, you can adjust according to the actual situation                // Similarly, if you are using Docker, you can use the following command:                String deleteImageCommand = "docker rmi " + imageName;
                executeCommand(deleteImageCommand);
            } catch (InterruptedException e) {
                ();
            }
        });
 
        // Close the thread pool        ();
 
        return "Mirror and container deleted";
    }
 
    // Method used to execute cmd command    private void executeCommand(String command) {
        try {
            // Use ProcessBuilder to execute commands            ProcessBuilder processBuilder = new ProcessBuilder((" "));
            Process process = ();
 
            // Call existing methods to print the output            printProcessOutput(process);
 
            // Wait for the process to end            int exitCode = ();
            if (exitCode != 0) {
                // Handling non-zero exit code may indicate an error in the execution of the command                ("Command executed with error. Exit code: " + exitCode);
            }
        } catch (IOException e) {
            // Handle IO exceptions that may be encountered during command execution            ();
        } catch (InterruptedException e) {
            // If the waitFor() method is interrupted, reset the interrupt status and process it            ().interrupt();
            ();
        } catch (Exception e) {
            // Handle possible exceptions in command string segmentation            ();
        }
    }

3. Develop other functions on this basis

Between generation and deletion, you can freely add and fine-tune some of the steps, such as deleting the CMD ["python", ""] in DockerFile, allowing the container to continue to run in the background, so that the code content can be modified through the file mapping relationship between the host and the container, and then run the code at the right time; and for example, creating a mirror that meets the needs, and then only creating and deleting the container to save server resources, etc.

4. Summary

This is the end of this article about using Java backend to operate Docker. For more related content on Java backend to operate Docker, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!