一、新建服务文件/etc/init.d/tomcat

  1. $ sudo vim /etc/init.d/tomcat
  2. #!/bin/sh
  3. ### BEGIN INIT INFO
  4. # Provides: tomcat
  5. # Required-Start: $remote_fs $network
  6. # Required-Stop: $remote_fs $network
  7. # Default-Start: 2 3 4 5
  8. # Default-Stop: 0 1 6
  9. # Short Description: the tomcat Java Application Server
  10. ### END INIT INFO
  11. RETVAL=0
  12. export JAVA_HOME=/usr/local/java
  13. export JRE_HOME=${JAVA_HOME}/jre
  14. export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib
  15. export CATALINA_HOME=/opt/tomcat
  16. export CATALINA_BASE=/opt/tomcat
  17. start()
  18. {
  19. if [ -f $CATALINA_HOME/bin/startup.sh ]
  20. then
  21. echo $"Starting Tomcat"
  22. $CATALINA_HOME/bin/startup.sh
  23. RETVAL=$?
  24. echo "OK"
  25. return $RETVAL
  26. fi
  27. }
  28. stop()
  29. {
  30. if [ -f $CATALINA_HOME/bin/shutdown.sh ]
  31. then
  32. echo $"Stopping Tomcat"
  33. $CATALINA_HOME/bin/shutdown.sh
  34. RETVAL=$?
  35. sleep 3
  36. ps -fwwu tomcat | grep apache-tomcat | grep -v grep | grep -v PID | awk '{print $2}'| xargs kill -9
  37. echo "OK"
  38. return $RETVAL
  39. fi
  40. }
  41. case "$1" in
  42. start)
  43. start
  44. ;;
  45. stop)
  46. stop
  47. ;;
  48. restart)
  49. echo $"Restarting Tomcat"
  50. $0 stop
  51. sleep 3
  52. $0 start
  53. ;;
  54. *)
  55. echo $"Usage:$0{start|stop|restart}"
  56. exit 1
  57. ;;
  58. esac
  59. exit $RETVAL

二、授权及配置

$ sudo chmod +x /etc/init.d/tomcat

## 新建服务需重启守护进程
$ sudo systemctl daemon-reload

## 设置开机自动启动
$ sudo systemctl enable tomcat

## 重启
$ sudo reboot