How to Use Monit to Monitor Your Java Application

Posted By : Jatin Gupta | 24-Feb-2018


Monit is a great opensource tool that consequently screens and manages server to guarantee that they remain online, as well as that the applications running, checksum etc are always right. Furthermore, monit accompanies a simple web UI through which the majority of the processes can be seen.


This blog covers how to monitor your Java application and restart it on failure.


If you are new to monitor you can refer this link to install and configure it. 


Let's get started,

To monitor a Java application, we can monitor it on the basis of the port number on which the application is running and the process name.
We can also monitor
it based on the pad file but if the application is killed forcefully using "kill -9" the pit file will not be deleted and in this case, monit will consider the application is running. So here we will see how to monitor on the basis of the port.

Let us create a file for the same in "/etc/monit/conf.d" directory with the name "java" 
Add the contents to the file :



check process java
        matching "java -jar app.jar"
        start program = "~/ start"
        stop program = "~/ stop"
        if failed port 8080 then restart 


> The "check process" keyword will check for the process named java matching the name "java  -jar"
> The start and stop program line will instruct monit with how to restart the program with the command mentioned after the keywords
> The file will contain the start and stop commands, here it is a little trick to use monit syntax with our use case.
> The "if failed port" will judge the application status and will restart the app if nothing is found on port 8080.


Now let us checkout the contents of the "" file



import sys
import os
action = sys.argv[1]
if action == 'start':
    os.system("java -jar /path/to/app.jar")
if action == 'stop':
    os.system("kill -9 $(pgrep java)")


This python script contains commands monit will run when it is instructed to start or stop our app.
If the script is called with "start" option, the command to start the app will be executed and same goes for the stop case.


After configuring this, restart the monit service and changes will be reflected. To confirm the same kill your java process and see that it is automatically restarted.


Monit also provides a nice simple UI which is accessible at "http://localhost:2812" . You can see the uptime of the app and other basic metrics here.


Hope this blog gave you an understanding of how to use monit for monitoring any java application.





Request for Proposal

Recaptcha is required.

Sending message..