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,
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
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 = "~/check.py start" stop program = "~/check.py 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 check.py 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 "check.py" file
#!/usr/bin/python2 import sys import os action = sys.argv 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.