iugo / blog

https://iugo.github.io/blog
3 stars 0 forks source link

Linux 運維, systemd 進程管理 #22

Open 2nini opened 6 years ago

2nini commented 6 years ago

systemd https://www.freedesktop.org/wiki/Software/systemd/

許多 Linux 發行版都已經内嵌了 systemd. 這裏使用的系統是 CentOS7, systemd 219.

systemd 意思是 system daemon. systemd 的使用簡單, 但是内在構造卻複雜.

在 systemd 中, 一切項目均爲 Unit. 我們最常用的服務是 Unit 的一種 type. 列出目前所有的服務的命令為: systemctl list-unit-files --type=service.

在這個列表中, 會看到服務有四種狀態, static, enabled, disabled, masked2.

Unit 配置文件存放地址及命名

每一個 Unit 都是一個文件, 這些文件一般儲存在 $SYSTEMD_UNIT_PATH 中. 如果沒有定義這個環境變量, 則可以參考 https://www.freedesktop.org/software/systemd/man/systemd.unit.html#Unit%20File%20Load%20Path 來查看 Unit 文件的存放路徑.

比如常见的用户创建的文件夹为 /etc/systemd/system.

因为 unit 存在多种 type, 所以命名的时候一般会标明, 命名方式为 ${name}.${type}.

service unit 的配置

一個 service unit 文件一般有三個部分, Unit 文档, Service 文档, Install 文档. 其中, Unit 和 Install 是通用的, 而 Service 是服务类型的 Unit 专属的.

其中, Service 除了上述的专属属性, 还有三个可能与其他 section 共用的属性: systemd.exec(5), systemd.kill(5) and systemd.resource-control(5)

來個例子:

[Unit]
Description=
Wants=
After= 
Requires=

[Service]
Type= 默認 simple, 可選 forking
EnvironmentFile= (属于 exec section)
Environment="TEST=1" 环境变量 (属于 exec section)
ExecStartPre=
ExecStart= 啓動命令
ExecStartPost=
KillMode= (属于 kill section)
Restart= 自动重启 常见值如 always
RestartSec= 重启前的等待时间, 默认为 100ms
PermissionsStartOnly= (存疑, 文档目前没找到)
User= (属于 exec section)
Group= (属于 exec section)
UMask= (属于 exec section)

[Install]
WantedBy= 常见值为 multi-user.target

关于 Wants, After, Requires 的区别, 该如何使用, 请参考: https://www.freedesktop.org/software/systemd/man/systemd.unit.html#%5BUnit%5D%20Section%20Options

在 KVM VPS 使用过程中, 我遇到过 main process exited, code=exited, status=255/n/a 这样的错误. 很奇怪的问题, 总在重启后解决. 在 OpenVZ VPS 中则没有这个问题.

在使用 Unit 的过程中, 主要用到以下几个命令:

systemctl enable <unit name> 启动服务
systemctl start <unit name> 开始服务
systemctl status <unit name> 查看状态
systemctl daemon-reload 重载
journalctl -u <unit name> 查看完整日志

參考:

iugo commented 2 years ago

为什么会出现 Unknown lvalue 'AmbientCapabilities' in section 'Service' 错误?

可能是 systemd 版本过低造成.

AmbientCapabilities 是什么:

https://unix.stackexchange.com/questions/580597/what-is-the-difference-between-ambientcapabilities-and-capabilityboundingset