Skip to content
Advertisement

How to add health endpoint in Apache Tomcat 9?

I am using Apache Tomcat 9 server as a Maven dependency in my project. It is working fine and now I need to add a health endpoint so that it will return 200 OK if everything is running fine.

I came to know about HealthCheckValve (https://tomcat.apache.org/tomcat-9.0-doc/config/valve.html#Health_Check_Valve) option in Tomcat 9 which is helpful. But I am not been able to figure out where to add this and the process of configuring this valve. As I know if server is standalone we can configure in Server.xml but as the Tomcat Server is a maven dependency I don’t know how and where I should configure this.

Can somebody please help me in configuring health endpoint in Apache Tomcat 9 (as a maven dependency) ?

Advertisement

Answer

I saw the documentation of all valves available in Tomcat 9.0.x.

In order to find the solution of this specific task, I tried looking for configuration of other valves such as Remote Address Valve in embedded tomcat.

I found a solution by user967710 after searching a lot.

I did the following to add a Health Check Valve to my Tomcat 9.0.64 :

        Tomcat tomcat = new Tomcat();

        tomcat.getEngine().setName(UUID.randomUUID().toString());

        tomcat.setPort(context.port);

        tomcat.setHostname(context.hostname);
        tomcat.getHost().setAppBase(".");
        
        Valve valve = new HealthCheckValve();
        
        tomcat.getHost().getPipeline().addValve(valve);

It doesn’t matter how you configure the Tomcat for your project i.e from line 1 ~ 5 but actually last 2 lines i.e 6 and 7 are important where you are adding the valve.

The health endpoint can be accessible on host:port/health. For e.g if it is hosted at http://localhost:4000 then the health endpoint would be http://localhost:4000/health

This endpoint will return 200 OK with a simple JSON response stating the Tomcat server status i.e “UP” if everything is up and running.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement