本文介绍了Linux如何使用Systemd和init.d配置服务


使用Systemd配置服务

开机初始化脚本

1
nano /etc/systemd/system/XXX.service

写入内容

1
2
3
4
5
6
7
8
9
10
11
[Unit]
Description=XXX Service
WorkingDirectory=/home/test/
Wants=network-online.target
After=network.target

[Service]
ExecStart= cmd

[Install]
WantedBy=multi-user.target

使用脚本

1
2
3
systemctl enable code-server.service
systemctl start code-server.service
systemctl status code-server.service

使用init.d配置服务

在init.d目录下增加启动脚本

1
nano /etc/init.d/aria2c 

添加脚本内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/sh

### BEGIN INIT INFO
# Provides: aria2
# Required-Start: $remote_fs $network
# Required-Stop: $remote_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: aria2 downloader
### END INIT INFO

case "$1" in
start)

echo -n "已开启Aria2c"
aria2c --conf-path=Aria2绝对路径aria2.conf -D
;;
stop)

echo -n "已关闭Aria2c"
killall aria2c
;;
restart)

killall aria2c
aria2c --conf-path=Aria2绝对路径/aria2.conf -D
;;
esac
exit

使用脚本

1
2
3
4
5
6
7
chmod 755 /etc/init.d/aria2c
update-rc.d aria2c defaults
systemctl enable aria2c
/lib/systemd/systemd-sysv-install enable aria2c
service aria2c start
service aria2c stop
service aria2c restart