参考 :
centos7下将java -jar命令运行一个项目做成systemd服务 - cdw0724 - 博客园
https://blog.csdn.net/weixin_39633134/article/details/115782572
CentOS6/7 -- 启动服务及日志查看_WEI的博客-CSDN博客_centos 查看服务日志
java服务为springboot服务
1.创建[install.sh]文件,粘贴以下内容
jar文件需要放入deploy_path定义的文件夹
需要修改前三行的配置
# 待修改配置 #
deploy_path=`pwd`
service_name=mytest
jar_name=mytest-1.0.jar
# 待修改配置 #
cat > $deploy_path/run.sh <<'EOF'
java -jar jar_name --spring.profiles.active=prod
EOF
sed -i "s#jar_name#$jar_name#g" $deploy_path/run.sh
cat > $deploy_path/service.sh <<'EOF'
#!/bin/bash
# 脚本所在目录
path="$( cd "$( dirname "$0" )" && pwd )"
JAR_NAME=jar_name
# System.getProperty("user.dir") 的目录及执行shell pwd的目录
cd $path
function start () {
cd $path
nohup sh run.sh >/dev/null 2>&1 &
exit 0
}
function stop () {
PID=`ps aux|grep "$JAR_NAME"|grep -v grep|awk '{print $2}'`
if [ -z $PID ];then
exit 0
else
kill -9 $PID
fi
}
function reload () {
PID=`ps aux|grep "$JAR_NAME"|grep -v grep|awk '{print $2}'`
if [ -z $PID ];then
exit 0
else
kill -1 $PID
fi
}
case "$1" in
start)
start
;;
stop)
stop
;;
reload)
reload
;;
restart)
stop
sleep 3
start
;;
*)
echo "start|stop|reload|restart"
;;
esac
EOF
sed -i "s#jar_name#$jar_name#g" $deploy_path/service.sh
sed -i "s#service_name#$service_name#g" $deploy_path/service.sh
cat > /etc/systemd/system/$service_name.service <<'EOF'
[Unit]
Description=Dibcn SDK application
After=syslog.target network.target
[Service]
Type=forking
Environment=JAVA_HOME=/usr/bin/java
ExecStart=deploy_path/service.sh start
ExecStop=deploy_path/service.sh stop
ExecReload=deploy_path/service.sh reload
PrivateTmp=true
RestartSec=5
Restart=always
[Install]
WantedBy=multi-user.target
EOF
sed -i "s#deploy_path#$deploy_path#g" /etc/systemd/system/$service_name.service
cat > bin.sh <<'EOF'
case "$1" in
start)
systemctl start service_name
;;
stop)
systemctl stop service_name
;;
restart)
systemctl restart service_name
;;
status)
systemctl status service_name
;;
log)
tail -f -n 200 logs/*/*.log
;;
log2)
journalctl -u service_name
;;
ps)
ps aux|grep jar_name
;;
*)
echo "start|stop|restart|status|log|ps"
;;
esac
EOF
sed -i "s#service_name#$service_name#g" $deploy_path/bin.sh
sed -i "s#jar_name#$jar_name#g" $deploy_path/bin.sh
# 给文件夹加权限
chmod -R 777 $deploy_path
# 重载unit配置文件
systemctl daemon-reload
# 设置开启自启
systemctl enable $service_name.service
2.部署
安装
sh install.sh
启动服务
./bin.sh start
查看服务状态
./bin.sh status
3.服务管理
# 启动服务
./bin.sh start
# 查看服务状态
./bin.sh status
# 停止服务
./bin.sh stop
# 重启服务
./bin.sh restart
# 查看服务日志
./bin.sh log