linux服务开机自启动

一、创建start.sh脚本

1.创建脚本

vim /opt/sjt/admin/start.sh

2.脚本内容

#!/bin/bash
if [ $# -eq 1 ];then
sleep $1
fi
#启动命令
/usr/bin/java -jar /opt/sjt/admin/sjt-admin-1.0.jar >> /opt/sjt/admin/admin.log 2>&1 &
#将pid写进文件
echo $! > /var/run/sjtadmin-service.pid

3.赋予脚本执行权限

chmod a+x /opt/sjt/admin/start.sh
二、创建System V服务脚本

service命令本身是一个shell脚本(称之为System V初始脚本),这种脚本保存在/etc/init.d目录中,它至少要支持start和stop命令。
1.创建脚本

vim /etc/init.d/sjtadmin

2.脚本内容

#!/bin/bash
# chkconfig: 2345 90 10 #运行级2,3,4,5下被启动或关闭,启动优先级90,关闭优先级10(数值越小优先级越大)
# description: sjtadmin service
PID_PATH=/var/run/sjtadmin-service.pid
Service_Name=sjtadmin-service

case "$1" in
start)
if [ $# -eq 2 ];then
/opt/sjt/admin/start.sh $2
else
/opt/sjt/admin/start.sh
fi
;;
stop)
kill $(cat ${PID_PATH})
rm ${PID_PATH}
;;
restart)
$0 stop
$0 start
;;
status)
if [ -e ${PID_PATH} ];then
echo "${Service_Name} is running, pid=$(cat ${PID_PATH})"
else
echo "${Service_Name} is NOT running"
exit 1
fi
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
esac

exit 0

3.脚本赋予执行权限

chmod a+x /etc/init.d/sjtadmin

4.chkconfig常用命令

chkconfig --list #列出所有服务启动情况
chkconfig --list mysqld #列出mysqld服务启动情况
chkconfig –level 25 mysqld on #配置系统启动时该脚本默认启动,默认在2、5等级
chkconfig mysqld on #配置系统启动时该脚本默认启动,默认在2、3、4、5等级
chkconfig mysqld off #配置系统启动时该脚本默认关闭
三、创建Systemd脚本,字母d是守护进程(daemon)的缩写

1.创建脚本

vim /usr/lib/systemd/system/sjtadmin.service

2.脚本内容

[Unit]
Description=sjt-admin service #服务的简单描述
Documentation=http://192.168.0.161:7000/swagger-ui.html#/ #服务文档
After=docker.service #本服务在docker.service之后启动

[Service]
User=root #服务运行的用户
Group=root #服务运行的用户组
Type=forking #父进程将会退出,子进程将成为主进程
Restart=no #退出后不会重启
KillMode=process #只杀主进程
ExecStart=/etc/rc.d/init.d/sjtadmin start 30
ExecStop=/etc/rc.d/init.d/sjtadmin stop

[Install]
WantedBy=multi-user.target

3.重新加载,让systemctl识别

systemctl daemon-reload

4.systemctl常用命令

#设置开机自启
systemctl enable sjtadmin
#关闭开机自启
systemctl disable sjtadmin
#启动服务
systemctl start sjtadmin
#停止服务
systemctl stop sjtadmin
#重启服务
systemctl restart sjtadmin
#查看服务状态
systemctl status sjtadmin
#检查开机自启状态
systemctl is-enabled sjtadmin

你可能感兴趣的:(部署,linux,服务器,bash)