Skip to content

Instantly share code, notes, and snippets.

@jonashackt
Last active May 5, 2021 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonashackt/59a405a5be94044cba754332089fb051 to your computer and use it in GitHub Desktop.
Save jonashackt/59a405a5be94044cba754332089fb051 to your computer and use it in GitHub Desktop.
Creating our own Java-based Docker Healthcheck without curl

Paketo.io / CloudNativeBuildPack created Container image doesn't have curl installed - and this is for good reasons (see https://stackoverflow.com/a/65393843/4964553 & https://blog.sixeyed.com/docker-healthchecks-why-not-to-use-curl-or-iwr/).

So we need another aproach... As suggested we should use the container inherited language (here: Java/JDK) to write our own healthcheck.

Creating our own Java-based Healthcheck without curl

So let's look at this great article https://mflash.dev/blog/2021/03/01/java-based-health-check-for-docker/ , where Naiyer explains how to write a simple healthcheck based on Java 11+

Here's my adoption leveraging an argument to provide a specific port. Just look into HealthCheck.java:

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
/*
 * Kudos to https://mflash.dev/blog/2021/03/01/java-based-health-check-for-docker/
 */
public class HealthCheck {

    public static void main(String[] args) throws InterruptedException, IOException {
        if(args.length == 0) {
            System.out.println("Please append the App's port like: java HealthCheck.java 8098");
            throw new RuntimeException("Argument port missing");
        }

        var request = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:" + args[0] + "/actuator/health"))
                .header("accept", "application/json")
                .build();

        var response = HttpClient.newHttpClient().send(request, BodyHandlers.ofString());

        if (response.statusCode() != 200 || !response.body().contains("UP")) {
            throw new RuntimeException("Healthcheck failed");
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment