一、新建服务文件/etc/init.d/tomcat
$ sudo vim /etc/init.d/tomcat
#!/bin/sh
### BEGIN INIT INFO
# Provides: tomcat
# Required-Start: $remote_fs $network
# Required-Stop: $remote_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short Description: the tomcat Java Application Server
### END INIT INFO
RETVAL=0
export JAVA_HOME=/usr/local/java
export JRE_HOME=${JAVA_HOME}/jre
export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib
export CATALINA_HOME=/opt/tomcat
export CATALINA_BASE=/opt/tomcat
start()
{
if [ -f $CATALINA_HOME/bin/startup.sh ]
then
echo $"Starting Tomcat"
$CATALINA_HOME/bin/startup.sh
RETVAL=$?
echo "OK"
return $RETVAL
fi
}
stop()
{
if [ -f $CATALINA_HOME/bin/shutdown.sh ]
then
echo $"Stopping Tomcat"
$CATALINA_HOME/bin/shutdown.sh
RETVAL=$?
sleep 3
ps -fwwu tomcat | grep apache-tomcat | grep -v grep | grep -v PID | awk '{print $2}'| xargs kill -9
echo "OK"
return $RETVAL
fi
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
echo $"Restarting Tomcat"
$0 stop
sleep 3
$0 start
;;
*)
echo $"Usage:$0{start|stop|restart}"
exit 1
;;
esac
exit $RETVAL
二、授权及配置
$ sudo chmod +x /etc/init.d/tomcat
## 新建服务需重启守护进程
$ sudo systemctl daemon-reload
## 设置开机自动启动
$ sudo systemctl enable tomcat
## 重启
$ sudo reboot