CentOS7和Ubuntu20之后的系统,如果希望服务开机启动,方便进行管理,可以使用systemctl
,具体的资料可以百度,这里只记录方法和重点。
下面我用caddy这个服务的生命周期来举例。
vim /etc/systemd/system/caddy.service
然后输入如下内容
[Unit]
Description=Caddy
Documentation=https://caddyserver.com/docs/
After=network.target
Requires=network.target
[Service]
Type=simple
ExecStart=/root/caddy/caddy run --config /root/caddy/Caddyfile
ExecReload=/root/caddy/caddy reload --config /etc/caddy/Caddyfile
ExecStop=/root/caddy/caddy stop
LimitNOFILE=1048576
LimitNPROC=512
KillMode=process
ProtectSystem=true
MemoryHigh=100M
TimeoutStopSec=5s
[Install]
WantedBy=multi-user.target
其中最需要关注的内容:
提醒下,写这个配置文件之前,可以先执行下上述3个命令,看看会不会有什么问题,比如文件没有执行缺陷,配置文件出错等等。
其他的其实很好理解,不懂可以参考这篇文章:
执行如下命令
# 刷新配置文件,每次变更配置文件后,必须执行
systemctl daemon-reload
# 启动caddy
systemctl start caddy
# 查看状态
systemctl status caddy
# 允许开机启动
systemctl enable caddy
关于服务文件的存放位置,之前看到不少教程,存放位置各有不同,所以专门查了下,先给推荐,放在如下位置:
/etc/systemd/system
原因如下所示,都是简单的单词就不翻译了:
In default Red Hat distributions,
/lib
is a symlink to/usr/lib
, but it appears those are different locations in Ubuntu.According to the systemd documentation,
/usr/lib/systemd/system/
is designated to hold upstream unit files that would not be edited by users and instead be provided and updated via packages.The
/etc/systemd/system
is designated as where user provided unit files would be. Packages should not override or update anything in/etc/systemd/system
. You can also use/etc/systemd/system
to override existing unit files.So using
/etc/systemd/system
should be the most compatible between different distributions.