本文已参与「新人创作礼」活动,一起开启掘金创作之路。
一、服务程序
用于需要长期运行、崩溃重启、开机自启的服务性程序
二、其他方案
rc-local.service 这是Linux系统默认提供的一个服务,方便快捷部署自启服务程序
具体创建方法为 在/etc/rc.local文件内添加服务程序的启动命令,系统在启动之后就会自动去加载 但是这种方式不够灵活,并且不能崩溃重启,不如自定义service的稳定可靠
三、创建方式
一切皆文件
通过编写服务文件来创建,通过服务操作指令来控制自启、启动
四、创建说明
1.文件名
文件路径: /etc/systemd/system/
文件名: [服务名].service
2.服务操作指令
命令: systemctl
参数:
- start: 启动程序
- stop: 关闭程序
- enable: 打开自启动
- disable: 关闭自启动
- is-active: 是否启动
- is-enabled: 是否打开自启动
3.文件说明
[Unit]
Description=服务程序的描述
ConditionPathExists=检测路径是否存在
ConditionFileIsExecutable=检测文件是否可执行
[Service]
Type=forking/simple #服务运行方式:后台/前台
ExecStartPre=启动程序前执行命令
ExecStart=启动程序命令
ExecStartPost=启动程序后执行命令
TimeoutStartSec=infinity #启动超时设为不超时
TimeoutSec=0 #启动超时设为0表示不超时
PrivateTmp=true #使用的tmp目录为私有隔离开的
Restart=always #无条件退出后重启
WorkingDirectory=/opt/App #设置进程的工作目录
User=root #设置进程的用户
[Install]
WantedBy=default.target
4.示例文件
[Unit]
Description=App
ConditionPathExists=/opt/App
ConditionFileIsExecutable=/opt/App/App
[Service]
Type=forking
ExecStart=sh /opt/App/startApp.sh &
TimeoutStartSec=infinity
TimeoutSec=0
PrivateTmp=true
Restart=always
WorkingDirectory=/opt/App
User=root
[Install]
WantedBy=default.target
5.示例操作
- 启动程序: systemctl start App.service
- 关闭程序: systemctl stop App.service
- 打开自启动: systemctl enable App.service
- 关闭自启动: systemctl disable App.service
- 是否启动: systemctl is-active App.service
- 是否打开自启动: systemctl is-enabled App.service