• Uncategorised
  • 0

Using docker API to listen to stop event in java

This code snippet is a great approach to listen for Docker events, particularly the stop events, using the HttpClient in Java without relying on a Docker client library. The code makes use of the Docker REST API and filters the stop events.

Here’s a breakdown of how the code works:

Key Concepts in the Code:

  1. Docker API URI:
    • The URI http://localhost:2375/events?filters={"event":["stop"]} connects to Docker’s API and streams only the events where containers are stopped (due to the event filter).
    • It assumes that the Docker daemon is configured to listen on port 2375 for HTTP requests (without TLS). If it’s on a Unix socket or other port, you might need to adjust this URL.
  2. HttpClient:
    • This code uses Java’s modern HttpClient (introduced in Java 11), which simplifies making HTTP requests.
    • It creates an HTTP GET request to the /events endpoint of the Docker API.
  3. Handling Docker Event Stream:
    • The event stream from Docker is a continuous flow of JSON objects. The code uses HttpResponse.BodyHandlers.ofInputStream() to get the raw stream and a Scanner to read each line of the response.
    • Since you’ve filtered for "stop" events at the API level, only stop events will be returned.
  4. Error Handling and Retrying:
    • In case of connection issues, the program catches the exception and waits for 5 seconds before trying again, ensuring robust handling of transient network or Docker daemon failures.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.InputStream;
import java.util.Scanner;

public class DockerEventListener {

    private static final String DOCKER_API_URI = "http://localhost:2375/events?filters={\"event\":[\"stop\"]}";

    public static void main(String[] args) {
        while (true) {
            try {
                listenForDockerEvents();
            } catch (Exception e) {
                System.out.println("Connection error: " + e.getMessage());
                System.out.println("Retrying in 5 seconds...");
                try {
                    Thread.sleep(5000); // Wait before retrying
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt(); // Handle thread interruption
                }
            }
        }
    }

    private static void listenForDockerEvents() throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(DOCKER_API_URI))
                .build();

        // Send request and handle response
        HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

        // Read the event stream
        try (Scanner scanner = new Scanner(response.body())) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println("Event: " + line); // Only stop events due to API filter
            }
        }
    }
}

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *