Systemctl
systemctl 命令
# 启动
systemctl start NAME.service
# 停止
systemctl stop NAME.service
# 重启
systemctl restart NAME.service
# 查看状态
systemctl status NAME.service
# 查看所有激活系统服务
systemctl list-units -t service
# 查看所有系统服务
systemctl list-units -t service -a
# 设置开机自启动
systemctl enable NAME.service
# 禁止开机自启动
systemctl disable NAME.service
# 查看服务是否是开机自启动
systemctl list-unit-files –t service
# 查看某服务是否开机自启动
systemctl is-enabled NAME.service
systemctl 状态
loaded:unit配置文件已处理
active(running):一次或多次持续处理的运行
active(exited):成功完成一次性配置
active(waiting):运行中,等待一个事件
inactive:不运行
enable:开机启动
disable:开机不启动
static:开机不启动,但可以被另一个启用的服务激活。
systemctl 运行级别
0 :关机:poweroff.target
1 :单用户模式:rescue.target
2 :默认不启用NFS的多用户:multi-user.target
3 :完全的多用户:multi-user.target
4 :保留:mult-user.target
5 :图形:graphical.target
6 :重启:reboot.target
自建服务
1、服务存放路径
用户级系统服务:/usr/lib/systemd/system
系统级系统服务:/etc/systemd/system
2、编写一个系统服务
创建系统服务文件的三个部分分别是:Unit 、 Service、 Install
Unit:
Description:描述信息
After:定义unit的启动次序,表示当前unit应该晚于哪些unit启动,其功能与Before相反;
Requires:依赖到的其它units,强依赖,被依赖的units无法激活时,当前unit即无法激活;
Wants:依赖到的其它units,弱依赖;
Conflicts:定义units间的冲突关系。
Service:
Type:定义影响ExecStart及相关参数功能的unit进程启动类型;
simple:默认值,这个daemon主要由ExecStart接的指令串来启动,启动后常驻于内存中;
forking:由ExacStart启动的程序透过spawns延伸出其它子程序来作为此deamon的主要服务。原生父程序在启动结束后就会终止。
oneshot:与simple类似,不过这个程序在完成工作后就结束,不常驻内存;
dbus:与simple类似,但这个daemon必须要在取得一个D-Bus的名称后,才会继续运作。因此通常也要同时设定BusName=才行;
notify:在启动完成后会发送一个通知消息。还需要配合NotifyAccess来让Systemd接收消息;
idle:与simple类似,要执行这个daemon必须要所有的工作都顺利执行完毕后才会执行。这类的daemon通常是开机到最后才执行即可的服务。
EnvironmentFile:环境配置文件;
ExecStart:指明启动unit要运行命令或脚本的绝对路径;
ExecStartPre:在ExecStart之前运行的绝对路径;
ExecStartPost:在ExecStart之后运行的绝对路径;
ExecStop:指明停止unit要运行的命令或脚本的绝对路径;
Restart:当设定Restart=1时,则当次daemon服务意外终止后,会再次自动启动。
PrivateTmp:true/false表示是否给服务分配独立的临时空间
Install:
Alias:别名,可使用systemctl command Alias.service
RequiredBy:被哪些units所依赖,强依赖;
WantedBy:被哪些units所依赖,弱依赖;
Also:安装本服务的时候还要安装别的相关服务。
以 node_exporter 举例:
cat > /usr/lib/systemd/system/node_exporter.service << EOF
[Unit]
Description=node_exporter
Documentation=https://prometheus.io/
After=network.target
[Service]
Type=simple
User=prometheus
ExecStart=/usr/local/node_exporter-1.1.2.linux-amd64/node_exporter --web.listen-address=:19918
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload && systemctl enable node_exporter.service && systemctl start node_exporter.service