Table of contents
1. Prepare the environment
1. Determine the location where the jar package and script files are stored.
For example, I store the jar package in the /home/project/ directory and the script file in the /home/project/sh/ directory.
2. Determine the location of java
#获取jdk位置(这个需要环境变量配置好才有效)
#第一种方法
echo $JAVA_HOME
# /usr/java/jdk1.8.0_211-amd64
#第二种方法
which java
# /usr/java/jdk1.8.0_211-amd64/bin/java
#第三种方法
whereis java
# java: /usr/bin/java /usr/java/jdk1.8.0_211-amd64/bin/java /usr/share/man/man1/java.1
We only need to make sure that the jdk directory is /usr/java/jdk1.8.0_211-amd64
2. Create new start and stop scripts
Write startup script:
# xxx是你的项目名,用英文或中文拼音都可以
vim /home/project/sh/xxx-service-start.sh
#!/bin/sh
# jdk目录
export JAVA_HOME=/usr/java/jdk1.8.0_211-amd64
export PATH=$PATH:$JAVA_HOME/bin
# 启动项目(如果不是root用户 需要在前面加sudo,在后面加密码)
nohup java -jar /home/project/xxx-dev1.3.1-8804.jar > /home/project/nohup.out 2>&1 &
# 导出项目启动的pid(用于关闭)
echo $! > /var/run/xxx-dev1.3.1-8804.pid
Write a stop script
vim /home/project/sh/xxx-service-stop.sh
#!/bin/sh
PID=$(cat /var/run/xxx-dev1.3.1-8804.pid)
kill -9 $PID
3. Increase file permissions
cd /home/project/sh
chmod -R 777 xxx-service-stop.sh
chmod -R 777 xxx-service-start.sh
cd /home/project
chmod -R 777 nohup.out
chmod -R 777 xxx-dev1.3.1-8804.jar
4. Configure system files
cd /usr/lib/systemd/system
touch xxx.service
#固定写法,换一下路径即可
#!/bin/sh
[Unit]
Description=xxx-service
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
ExecStart=/home/project/xxx-service-start.sh
ExecStop=/home/project/xxx-service-stop.sh
PrivateTmp=true
[Install]
WantedBy=multi-user.target
5. Execute orders
#将jar添加到开机自启服务中
systemctl enable xxx.service
#系统服务刷新
systemctl daemon-reload
6. Start the service
#启动服务
systemctl start xxx.service
#查看服务状态
systemctl status xxx
#停止服务
systemctl stop xxx
#取消开机自启
systemctl disable xxx