利用sctl管理你自己的服务启动脚本
简介
在前面的微头条,我们讲到了我们不需要容器。那么问题来了。我们怎么启动我们的服务呢?linux下面常用的启动程序,有systemd和supervisor, supervisor是python写的。 systemd是很多linux自带的启动管理程序。
今天给大家讲解如何通过一个自定义的 脚本,来帮助我们管理systemd服务
原理
我们管理systemd服务的原理,就是把我们的服务启动配置文件,加到/etc/systemd/system/这个默认的目录下面
sctl脚本
这个脚本,可以在github上面搜索netroby/sctl, 源代码如下
#!/bin/sh
BASEPATH=$(pwd)
echo $BASEPATH
case $1 in
'enable') echo 'enable service'
set -ex
ln -s $BASEPATH/system/${2}.service /etc/systemd/system/${2}.service
systemctl enable ${2}.service
systemctl restart ${2}.service
set +ex
;;
'disable') echo 'disable service'
set -ex
systemctl stop ${2}.service
systemctl disable ${2}.service
set +ex
if [ -f /etc/systemd/system/${2}.service ]; then
set -ex
unlink /etc/systemd/system/${2}.service
set +ex
else
echo "File /etc/systemd/system/${2}.service not exists, do not need to unlink"
fi
;;
'start') echo 'start service'
set -ex
systemctl daemon-reload
systemctl restart ${2}.service
set +ex
;;
'stop') echo 'stop service'
set -ex
systemctl stop ${2}.service
set +ex
;;
'status') echo 'status of service'
set -ex
systemctl status ${2}.service
set +ex
;;
'logs') echo 'view logs of service'
set -ex
journalctl -xe -u ${2} -f
set +ex
;;
*)echo "Usage: ${0} enable|disable|start serviceName"
;;
esac
我们创建任意一个目录,然后保存上面的内容为sctl文件,然后设置为可写,并加到/usr/bin/sctl的软连接
chmod a+x sctl
ln -s $(pwd)/sctl /usr/bin/sctl
接下来,我们创建一个测试用的systemd服务文件hello.service,就放到当前目录的system子目录下面(建一个子目录为system)
内容如下
[Unit]
Description=Hello Service
After=network.target
Wants=network.target
[Service]
Type=oneshot
ExecStart=/bin/ls -al
[Install]
WantedBy=multi-user.target
测试我们的sctl功能
sctl enable hello
sctl status hello
sctl logs hello
sctl的几个命令介绍
sctl脚本,提供了几个命令
- enable 创建service链接,并启动服务+设置服务自启动
- disable 删除服务和删除自启动
- start 重载systemd配置,并重启服务
- stop 停止服务
- status 查看服务状态
- logs 查看服务产生的日志
分类: Linux/Unix 标签: 脚本 systemd sctl 启动 发布于: 2020-12-26 19:05:59, 点击数: