Systemd 是 Linux 系统工具,最常用来启动守护进程服务,功能非常强大。

Systemd是一组命令,涉及系统管理的多方面,这里只说systemctl相关的命令。

systemd有系统和用户区分:

  • 系统(/user/lib/systemd/system/)
  • 用户(/etc/lib/systemd/user/)

一般系统管理员手工创建的单元文件建议存放在/etc/systemd/system/目录下面。

每一个服务以.service结尾,一般会分为3部分:[Unit]、[Service]和[Install],例如:

创建service

/usr/lib/systemd/system 下创建 test.service 文件内容如下:

首先创建service:
[Unit]
Description=Tool Matrix Server
After=network.target
After=syslog.target

[Service]
Type=forking
PIDFile=/var/run/tool_matrix.pid
ExecStart=/home/www/tool_build/gin-vue-admin
ExecStop=/bin/kill $MAINPID
ExecReload=/bin/kill -USR1 $MAINPID;
Restart=always

[Install]
WantedBy=multi-user.target graphical.target

tips:

[Unit]

Description : 服务的简单描述

Documentation : 服务文档

After= : 依赖,仅当依赖的服务启动之后再启动自定义的服务单元

[Service]

Type : 启动类型simple、forking、oneshot、notify、dbus

Type=simple(默认值):systemd认为该服务将立即启动。服务进程不会fork。如果该服务要启动其他服务,不要使用此类型启动,除非该服务是socket激活型。 Type=forking:systemd认为当该服务进程fork,且父进程退出后服务启动成功。对于常规的守护进程(daemon),除非你确定此启动方式无法满足需求,使用此类型启动即可。使用此启动类型应同时指定 PIDFile=,以便systemd能够跟踪服务的主进程。 Type=oneshot:这一选项适用于只执行一项任务、随后立即退出的服务。可能需要同时设置 RemainAfterExit=yes 使得 systemd 在服务进程退出之后仍然认为服务处于激活状态。 Type=notify:与 Type=simple 相同,但约定服务会在就绪后向 systemd 发送一个信号。这一通知的实现由 libsystemd-daemon.so 提供。 Type=dbus:若以此方式启动,当指定的 BusName 出现在DBus系统总线上时,systemd认为服务就绪。

PIDFile : pid文件路径

ExecStart:启动

ExecReload:重载

ExecStop:停止

[Install]

WantedBy:服务安装的用户模式,从字面上看,就是想要使用这个服务的有是谁?上文中使用的是:multi-user.target ,就是指想要使用这个服务的目录是多用户。每一个.target实际上是链接到我们单位文件的集合,当我们执行:

sudo systemctl enable test.service

就会在/etc/systemd/system/multi-user.target.wants/目录下新建一个/usr/lib/systemd/system/test.service 文件的链接。

操作service
#启动服务
$ sudo systemctl start test.service

#查看日志
$ sudo journalctl -f -u test.service

#重启
$ sudo systemctl restart test.service

#重载
$ sudo systemctl reload test.service

#停止
$ sudo systemctl stop test.service