linux注册自启动服务

linux注册自启动服务

方法一:使用Service管理开启自启动

/etc/init.d/中增加配置文件,使用chkconfig命令就可以注册到Service服务自启动

创建配置注册并管理Service管理服务

  1. /etc/init.d/创建配置文件test

    touch /etc/init.d/test
    
  2. 配置内容如下

    # 数字意义: 2345表示系统运行级别是2,3,4或者5时都启动此服务,80:启动优先级,90停止优先级,数字越大越后执行
    # chkconfig 2345 80 90
    # description: 启动redis服务
    # 这里后面都写要执行脚本命令
    touch /home/test/test.txt
    
  3. 给配置脚本增加权限

    chmod a+x /etc/init.d/test
    
  4. 添加到chkconfig服务

    chkconfig --add test
    
  5. 然后可以使用service命令管理服务

service test start 
# 还有其他命令 stop restart status

chkconfig命令详解

  • chkconfig --list #列出所有的系统服务
  • chkconfig --add redisTest #增加redisTest服务
  • chkconfig --del redisTest #删除redisTest服务
  • chkconfig --level redisTest2345 on/off #设置redisTest在运行级别为2、3、4、5的情况下都是on(开启)/off(关闭)的状态
  • chkconfig --list redisTest #列出redisTest服务设置情况

方法二:使用systemctl管理开启自启动

Linux系统最新的初始化系统是systemd,可以提高系统的启动速度,尽可能启动较少的进程,尽可能多进程并发启动,对应的进程管理命令是systemctl

注册systemctl管理的服务

在这里,我们用docker 注册自启动服务的配置文件作为案例进行介绍

  1. /usr/lib/systemd/system目录下新增docker.service文件,并建立软连接

    touch /usr/lib/systemd/system/docker.service
    ln -s  '/usr/lib/systemd/system/docker.service'  '/etc/systemd/system/docker.service' 
    
  2. docker.service文件内容如下

    [Unit]
    Description=Docker Application Container Engine #当前配置文件的描述信息
    Documentation=https://docs.docker.com
    After=network-online.target firewalld.service  #表示当前服务是在那个服务后面启动,一般定义为网络服务启动后启动
    Wants=network-online.target
    [Service] 
    Type=notify	#定义启动类型
    ExecStart=/usr/bin/dockerd	#定义启动进程时执行的命令。
    ExecReload=/bin/kill -s HUP $MAINPID #重启服务时执行的命令
    LimitNOFILE=infinity
    LimitNPROC=infinity
    TimeoutStartSec=0
    Delegate=yes
    KillMode=process
    Restart=on-failure
    StartLimitBurst=3
    StartLimitInterval=60s
    [Install]
    WantedBy=multi-user.target #表示多用户命令行状态
    
  3. docker.service添加权限

    chmod a+x /etc/systemd/system/docker.service
    
  4. 重新加载配置文件

    systemctl daemon-reload  
    
  5. 启动/重启/查看状态

    systemctl  start/stop/restart/status docker
    
  6. 设置开机启动

    systemctl enable docker.service
    

    原理:会在/etc/systemd/system/multi-user.target.wants/这个linux系统自启动目录下新建一个/usr/lib/systemd/system/docker.service 文件的链接

systemctl命令详解的链接地址

linux的.service文件配置详解

方法三:使用/etc/rc.d/rc.local 开启自启动

linux系统在开启后,会执行/etc/rc.d/rc.local里的脚本,只需要创建脚本,然后再/etc/rc.d/rc.local中调用就可以了,但是推荐使用上面两种

  1. 创建脚本

    touch /home/test/test.sh
    
  2. 赋予权限

    chmod a+x /home/test/test.sh
    
  3. 命令追加到/etc/rc.d/rc.local

    # 这里必须是绝对路径
    /home/test/test.sh
    

猜你喜欢

转载自blog.csdn.net/blood_Z/article/details/128848018