Lahiru Chandima
Lahiru Chandima

Reputation: 24088

Terminate tomcat if port is already occupied

I have a web application which runs on tomcat and reports its status to another monitoring application (this monitoring application monitors several other processes in the system).

If the app gets deployed successfully in tomcat, the monitoring application shows that the app is live and operational.

But, if tomcat fails to listen on the port which is configured in Connector element in serer.xml, still the app gets deployed, so it is shown as live in the monitoring application. But, users cannot actually access the web application since the web server is not listening on the configured port.

Is there a way I can configure tomcat so that it will terminate (or at least not deploy the webapps) if it fails to listen on the server port?

Upvotes: 2

Views: 158

Answers (2)

Shmulik Klein
Shmulik Klein

Reputation: 3914

I found this gist which might help you to implement a logic that binds to Tomcat's init event and checks for status of its components (according to the comments in the gist, you might already find a maven artifact which do the same).

Create a lifecycle listener, something like ConnectorListener and make it implement the LifeCycleListener interface. Then put the code from the gist into the overrided lifeCycleEvent method (you should make some adjustments to make it fit).

Then add it to your web.xml under <engine> tags.

Upvotes: 1

sozkul
sozkul

Reputation: 675

You can write some script in {tomcat_setup}/bin/startup.sh file.

Add below script after line contains EXECUTABLE=catalina.sh.

parent=`dirname "$PRGDIR"`
file="$parent"/conf/server.xml
host=`hostname`
#get ports from server.xml
for i in `grep -o "<Connector port=\".*\"" "$file" | cut -d\" -f2`;
do
  #check port is listening
  ret=`cat < /dev/null > /dev/tcp/"$host"/"$i"`
  if [ $? -eq 0 ]; then
        echo "Tomcat is already working!"
        exit 1
  fi
done

Upvotes: 0

Related Questions