Linux设置开机自启动service

什么是Systemctl

Systemctl是一个Systemd工具,主要负责控制Systemd系统和服务管理器。

什么是Systemd

systemd为系统的启动和管理提供一套完整的解决方案。

The advantages of Systemd are that it's powerful and easy to use. The disadvantages are that it's huge and complex. In fact, ​many people opposes Systemd on the grounds that it is too complex and strongly coupled with the rest of the operating system, and they think that it violates the Unix philosophy of "keep simple, keep stupid".

systemdcommand3.png (Systemd架构图)

systemd可以管理所有系统资源。不同的资源统称为Unit(单元)。

每一个Unit都有一个配置文件,告诉Systemd怎么启动这个Unit 。

Systemd默认从目录/etc/systemd/system/读取配置文件。但是,里面存放的大部分文件都是符号链接,指向目录/usr/lib/systemd/system/,真正的配置文件存放在那个目录。

systemctl enable命令用于在上面两个目录之间,建立符号链接关系。

设置开机自启动service

新建配置文件

vim /etc/systemd/system/web-shell.service

[Unit]
Description=k8s web shell
After=docker.service
Requires=docker.service

[Service]
ExecStart=/usr/bin/sh /home/xxx/web-shell/start-web-shell.sh
Restart=on-failure

[Install]
WantedBy=multi-user.target

wq!

设置开机自启动

  • 加载配置文件
sudo systemctl daemon-reload web-shell
  • 开启自启动
sudo systemctl enable web-shell
  • 启动服务
sudo systemctl start web-shell
  • 停止服务
sudo systemctl stop web-shell
  • 查看服务状态
systemctl status web-shell

● web-shell.service - k8s web shell
   Loaded: loaded (/etc/systemd/system/web-shell.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2019-10-29 20:30:08 CST; 17h ago
 Main PID: 23090 (sh)
    Tasks: 22
   Memory: 5.1M
   CGroup: /system.slice/web-shell.service
           ├─23090 /usr/bin/sh /home/xxx/web-shell/start-web-shell.sh
           └─23092 ./bin/k8s-webshell-linux

done!

配置文件区块说明

Unit

定义元数据以及配置与其他Unit的关系

Description:简短描述 After:如果该字段指定的Unit也要启动,那么必须在当前Unit之前启动 Requires:当前Unit依赖的其他Unit,如果它们没有运行,当前Unit会启动失败

Service

ExecStart:启动当前服务的命令 Restart:定义何种情况systemd会自动重启当前服务,可能的值包括always(总是重启)、on-success、on-failure、on-abnormal、on-abort、on-watchdog

Install

定义如何启动以及是否开机启动

WantedBy:它的值是一个或多个Target,当前Unit激活时(enable)符号链接会放入/etc/systemd/system目录下面以Target名 + .wants后缀构成的子目录中

更详细的说明可以通过 man systemd.service查看

参考: Learn Systemd Commands In 20 Minutes

0 0 投票数
Article Rating
订阅评论
提醒
guest
0 评论
最旧
最新 最多投票
内联反馈
查看所有评论
0
希望看到您的想法,请您发表评论x