服务主要以service为扩展名,文件路径为/usr/lib/systemd/system/。需要用root用户操作
1、创建服务文件
以tomcat服务为例,使用命令创建服务文件:
touch /usr/lib/systemd/system/tomcat.service
2、编写服务内容
vim /usr/lib/systemd/system/tomcat.service
[Unit]
Description=Apache Tomcat
After=network-online.target
Wants=network-online.target
[Service]
Type=forking
ExecStart=/www/tomcat/bin/deploy.sh start
ExecReload=/www/tomcat/bin/deploy.sh restart
ExecStop=/www/tomcat/bin/deploy.sh stop
User=wangjs
Group=wangjs
[Install]
WantedBy=multi-user.target
其中[Service]模块下的Type分为forking与simple两种:
区别在于执行脚本时会不会独占shell,如果可以后台运行,则使用forking,否则使用simple。
比如tomcat/nginx应用启动后会自动后台运行,则使用forking,而java -jar *.jar命令运行后会独占shell,则使用simple。
注意User/Group如果不写则默认以root用户运行,如果指定需要手动添加。
3、加载服务
服务内容编写或修改之后需要对systemd重新加载服务才能生效:
systemctl daemon-reload
4、配置服务开机启动
systemctl enable tomcat 配置开机启动
systemctl cat tomcat 查看服务内容
systemctl start tomcat 启动服务
systemctl stop tomcat 停止服务
systemctl status tomcat 查看服务状态
5、脚本中 deploy.sh 分享
#!/bin/bash
PROG_NAME=$0
ACTION=$1
APP_START_TIMEOUT=120
APP_PORT=2021
HEALTH_CHECK_URL=http://127.0.0.1:${APP_PORT}
APP_NAME=tomcat
usage() {
echo "Usage: $PROG_NAME {start|stop|restart}"
exit 2
}
health_check() {
exptime=0
echo "checking ${HEALTH_CHECK_URL}"
while true
do
status_code=`/usr/bin/curl -L -o /dev/null --connect-timeout 5 -s -w %{http_code} ${HEALTH_CHECK_URL}`
if [ "$?" != "0" ]; then
echo -n -e "\rapplication not started"
else
echo "code is $status_code"
if [ "$status_code" == "200" ];then
break
fi
fi
sleep 1
((exptime++))
echo -e "\rWait app to pass health check: $exptime..."
if [ $exptime -gt ${APP_START_TIMEOUT} ]; then
echo 'app start failed'
exit 1
fi
done
echo "check ${HEALTH_CHECK_URL} success"
}
start_application() {
echo "starting java process"
bash /www/tomcat/bin/startup.sh
echo "started java process"
}
stop_application() {
checkjavapid=`ps -ef | grep java | grep ${APP_NAME} | grep -v grep |grep -v 'deploy.sh'| awk '{print$2}'`
if [[ ! $checkjavapid ]];then
echo -e "\rno java process"
return
fi
echo "stop java process"
times=60
for e in $(seq 60)
do
sleep 3
COSTTIME=$(($times - $e ))
checkjavapid=`ps -ef | grep java | grep ${APP_NAME} | grep -v grep |grep -v 'deploy.sh'| awk '{print$2}'`
if [[ $checkjavapid ]];then
kill $checkjavapid
echo -e "\r -- stopping java lasts `expr $COSTTIME` seconds."
else
echo -e "\rjava process has exited"
break;
fi
done
echo ""
}
start() {
start_application
health_check
}
stop() {
stop_application
}
case "$ACTION" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
usage
;;
esac