Centos7.3_x86_64通过systemctl控制tomcat8.0.46启动和停止

时间:2022-09-01 08:27:24
Centos7.3_x86_64通过systemctl控制tomcat8.0.46启动和停止


之前在centos 6上通过脚本控制tomcat 启动和停止的脚本,虽然在centos 7也可以使用,但centos 7的守护进程已经由centos6的init更换为systemctl,因此可以通过systemctl控制tomcat的启动和停止,另外经测试通过systemctl启动和关闭tomcat非常成功,尤其是关闭tomcat,之前时候catalina.sh脚本关闭tomcat,会有无法关闭的情况,而使用了systemctl后可以确保百分百关闭成功,具体过程如下:

配置java环境变量
# vim
/etc/profile
export JAVA_HOME
=/usr/java/jdk1.8.0_111
export PATH
=$JAVA_HOME/bin:$PATH


1.编辑/etc/sudoers,目的为可以让普通用于远程没有tty的情况下重启tomcat:

#Defaults requiretty #不需要tty
tomcat ALL
=(ALL) NOPASSWD: /usr/bin/systemctl #tomcat用户使用sudo 执行systemctl命令不需要输入密码

2.添加tomcat用户:

# useradd tomcat
-u 1000 #此用户用于后期启动tomcat,应用不要用root身份启动

3.创建tomcat软连接:

[root@node1 local]#
ln -sv /usr/local/apache-tomcat-8.0.46 /usr/local/tomcat
/usr/local/tomcat’ -> ‘/usr/local/apache-tomcat-8.0.46

4.编辑tomcat启动脚本tomcat.service文件
注意:文件中目录路径必须是绝对路径

# vim
/usr/lib/systemd/system/tomcat.service
[Unit]
Description
=Tomcat8
After
=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type
=forking
PIDFile
=/usr/local/tomcat/tomcat.pid
ExecStart
=/usr/local/tomcat/bin/startup.sh
ExecReload
=/bin/kill -s HUP $MAINPID
ExecStop
=/bin/kill -s QUIT $MAINPID
PrivateTmp
=true
User
=tomcat
Group
=tomcat

[Install]
WantedBy
=multi-user.target


[unit]配置了服务的描述,规定了在network启动之后执行,
[service]配置服务的pid,服务的启动,停止,重启
[
install]配置了使用用户

5.编辑变量脚本/usr/local/tomcat/bin/setenv.sh

# vim
/usr/local/tomcat/bin/setenv.sh

export CATALINA_HOME
=/usr/local/tomcat
export CATALINA_BASE
=/usr/local/tomcat
#设置Tomcat的PID文件
CATALINA_PID
="$CATALINA_BASE/tomcat.pid"
#添加JVM选项
JAVA_OPTS
="-server -XX:PermSize=256M -XX:MaxPermSize=1024m -Xms512M -Xmx1024M -XX:MaxNewSize=256m"

#
chmod a+x /usr/local/tomcat/bin/setenv.sh

6.测试Tomcat.service服务

启动tomcat:
#
su - tomcat
#
sudo systemctl start tomcat

[tomcat@node1
~]$ systemctl status tomcat
● tomcat.service
- Tomcat8
Loaded: loaded (
/usr/lib/systemd/system/tomcat.service; disabled; vendor preset: disabled)
Active: active (running) since Sun
2018-02-25 14:59:06 CST; 1min 52s ago
Process:
14030 ExecStop=/bin/kill -s QUIT $MAINPID (code=exited, status=0/SUCCESS)
Process:
14041 ExecStart=/usr/local/tomcat/bin/startup.sh (code=exited, status=0/SUCCESS)
Main PID:
14055 (java)
CGroup:
/system.slice/tomcat.service
└─
14055 /usr/bin/java -Djava.util.logging.config.file=/usr/local/tomcat/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogMan..


因为配置pid,在启动的时候会再tomcat根目录生成tomcat.pid文件,停止之后删除。

同时tomcat在启动时候,执行start不会启动两个tomcat,保证始终只有一个tomcat服务在运行。

多个tomcat可以配置在多个目录下,互不影响。