Home > OS >  How to add health endpoint in Apache Tomcat 9?
How to add health endpoint in Apache Tomcat 9?

Time:09-30

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) ?

CodePudding user response:

See the documentation, then add the HealthCheckerValve to server.xml. Valves go into either the Engine, Host or Context element. In the server.xml packaged with Tomcat you can find comments that should direct you to the right location.

When embedding a version of Tomcat, you won't have this file available, and so you need to assemble instances of these containers programmatically.

Check the launcher application in this example: https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/basic_app_embedded_tomcat/basic_app-tomcat-embedded.html While I could not find methods like addValve() I found an init() method that you could use to provide a server.xml which will be read by Tomcat.

CodePudding user response:

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.

  • Related