How to add Tomcat as Service Linux Machine: In this tutorial, we will see how to make tomcat server as a service in Linux machine.

Tomcat is the most used server for deploying Java applications. Tomcat can be installed as service using the installer in windows machine but in Linux machine, it’s not simple as windows machines

To set up Tomcat server, you need to install JRE First

  • Install  JRE on the Linux machine and setup the environment variables to make sure that your JRE is installed execute the command java -version in Terminal
  • If JRE is configured correctly then you will be seeing the version of your installed JRE

How to Install Tomcat:

unzip downloadedfilename.zip
  • After unzip go to the bin folder and try to execute the command below
sudo sh startup.sh
  • To see tomcat is working fine & stop the server

Now actual service creation procedure will start

  • Login as root into Linux machine with sudo -i or su -i
  • Type the below command
  • Create a file in folder using command vi /etc/init.d/tomcat.service

then paste the below code

#!/bin/sh

### BEGIN INIT INFO
# Provides:          tomcat
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start and stop Apache Tomcat
# Description:       Enable Apache Tomcat service provided by daemon.
### END INIT INFO
 
ECHO=/bin/echo
TEST=/usr/bin/test
TOMCAT_USER=ec2-user
TOMCAT_HOME=/opt/tomcat
TOMCAT_START_SCRIPT=$TOMCAT_HOME/bin/startup.sh
TOMCAT_STOP_SCRIPT=$TOMCAT_HOME/bin/shutdown.sh
 
$TEST -x $TOMCAT_START_SCRIPT || exit 0
$TEST -x $TOMCAT_STOP_SCRIPT || exit 0
 
start() {
    $ECHO -n "Starting Tomcat"
    su - $TOMCAT_USER -c "$TOMCAT_START_SCRIPT &"
    $ECHO "."
}
 
stop() {
    $ECHO -n "Stopping Tomcat"
    su - $TOMCAT_USER -c "$TOMCAT_STOP_SCRIPT 60 -force &"
    while [ "$(ps -fu $TOMCAT_USER | grep java | grep tomcat | wc -l)" -gt "0" ]; do
        sleep 5; $ECHO -n "."
    done
    $ECHO "."
}
 
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        sleep 30
        start
        ;;
    *)
        $ECHO "Usage: tomcat {start|stop|restart}"
        exit 1
esac
exit 0
  • Change TOMCAT_USER value with respective user
  • change TOMCAT_HOME Tomcat Directory according to your path location

Save the file by type SHIFT + ; and wq  and Enter

type below command to update service

sudo update-rc.d tomcat defaults

then type below command to enable in it to start at boot time

sudo systemctl enable tomcat.service

to start, stop, restart use below commands

systemctl start tomcat
systemctl stop tomcat
systemctl restart tomcat

Thank You

Also Read: Creating Topic Zookeeper/Kafka Server

How to add Tomcat as Service Linux Machine

Leave a Reply

Your email address will not be published. Required fields are marked *