Debian10 添加系统服务(systemctl管理)

Debian10 添加系统服务(systemctl管理)

检查是否安装了systemctl

可以使用以下命令进行检查

1

# systemd –version

如果没有安装可以网上搜索看系统是否支持安装

创建服务文件

服务文件的目录在

1

cd /lib/systemd/system

新建服务文件,简单模板如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

[Unit]
# 简短描述
Description=node_exporter
# 文档描述
Documentation=node_exporter Monitoring System
# 如果该字段指定的 Unit 也要启动,那么必须在当前 Unit 之前启动
After=network.target

[Service]
User=服务启动的用户名
Group=用户所在组名
ExecStart=可执行程序的路径

[Install]
WantedBy=multi-user.target

保存文件为test.service

启动服务

 

1

systemctl start test

 

systemctl 文件块字段说明

Unit 块

1
2
3
4
5
6
7
8
9
10

Description:简短描述
Documentation:文档地址
Requires:当前 Unit 依赖的其他 Unit,如果它们没有运行,当前 Unit 会启动失败
Wants:与当前 Unit 配合的其他 Unit,如果它们没有运行,当前 Unit 不会启动失败
BindsTo:与Requires类似,它指定的 Unit 如果退出,会导致当前 Unit 停止运行
Before:如果该字段指定的 Unit 也要启动,那么必须在当前 Unit 之后启动
After:如果该字段指定的 Unit 也要启动,那么必须在当前 Unit 之前启动
Conflicts:这里指定的 Unit 不能与当前 Unit 同时运行
Condition…:当前 Unit 运行必须满足的条件,否则不会运行
Assert…:当前 Unit 运行必须满足的条件,否则会报启动失败

Install 块

1
2
3
4

WantedBy:它的值是一个或多个 Target,当前 Unit 激活时(enable)符号链接会放入/etc/systemd/system目录下面以 Target 名 + .wants后缀构成的子目录中
RequiredBy:它的值是一个或多个 Target,当前 Unit 激活时,符号链接会放入/etc/systemd/system目录下面以 Target 名 + .required后缀构成的子目录中
Alias:当前 Unit 可用于启动的别名
Also:当前 Unit 激活(enable)时,会被同时激活的其他 Unit

Service 块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Type:定义启动时的进程行为。它有以下几种值。
Type=simple:默认值,执行ExecStart指定的命令,启动主进程
Type=forking:以 fork 方式从父进程创建子进程,创建后父进程会立即退出
Type=oneshot:一次性进程,Systemd 会等当前服务退出,再继续往下执行
Type=dbus:当前服务通过D-Bus启动
Type=notify:当前服务启动完毕,会通知Systemd,再继续往下执行
Type=idle:若有其他任务执行完毕,当前服务才会运行
ExecStart:启动当前服务的命令
ExecStartPre:启动当前服务之前执行的命令
ExecStartPost:启动当前服务之后执行的命令
ExecReload:重启当前服务时执行的命令
ExecStop:停止当前服务时执行的命令
ExecStopPost:停止当其服务之后执行的命令
RestartSec:自动重启当前服务间隔的秒数
Restart:定义何种情况 Systemd 会自动重启当前服务,可能的值包括always(总是重启)、on-success、on-failure、on-abnormal、on-abort、on-watchdog
TimeoutSec:定义 Systemd 停止当前服务之前等待的秒数
Environment:指定环境变量

附官方说明:https://www.freedesktop.org/software/systemd/man/systemd.unit.html

 systemctl 常用命令

 

1
2
3
4
5
6
7
8
9

systemctl start node_exporter  开启服务
systemctl stop node_exporter   关闭服务
systemctl restart node_exporter    重启服务
systemctl status node_exporter    查看服务状态
systemctl enable node_exporter    将服务设置为开机自启动
systemctl disable node_exporter    禁止服务开机自启动
systemctl is-enabled node_exporter    查看服务是否开机启动
systemctl list-unit-files|grep enabled    查看开机启动的服务列表
systemctl –failed    查看启动失败的服务列表

© 版权声明
THE END
喜欢就支持一下吧
点赞5赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容