Linux 系统注册系统服务流程

  • 在/etc/systemd/system定义test.service文件(以定义启动nginx服务为例子)
[Unit]
Description=nginx service
Documentation=this is a test system service

[Service]
Type=notify
# 启动服务时的等待的秒数,TimeoutStartSec 的值指定为 0,从而关闭超时检测。
TimeoutStartSec=0
# 工作目录
WorkingDirectory=/root/nginx
# 服务运行用户
User=root
# 服务运行用户组
Group=root
Restart=on-failure
RestartSec=42s
ExecStart=/root/nginx/start.sh
ExecStop=/root/nginx/stop.sh

[Install]
WantedBy=multi-user.target
 Type:定义启动类型
  - simple 默认值,ExecStart字段启动的进程为主进程。主进程启动,服务启动,主进程结束,服务结束。
  - forking: ExecStart字段将以fork()方式启动,此时父进程将会退出,子进程将成为主进程。
  • 定义service服务启动、停止、重启所需要的脚本
    启动脚本start.sh:
#!/bin/bash
nginx -c /etc/nginx/nginx.conf

停止脚本stop.sh:

#!/bin/bash
nginx -s stop
  • 执行systemctl或者service命令进行启动、停止
# 注册服务开机自启
systemctl enable test.service
# 刷新系统服务
systemctl daemon-reload
# 启动服务
systemctl start test.service
# 停止服务
systemctl stop test.service

更多推荐

Linux 系统注册系统服务流程