zoukankan      html  css  js  c++  java
  • linux 服务开机自启动systemd方式 (Centos7)

     linux 服务开机自启动systemd方式 (Centos7)

    1、编写一个 /opt/hello.sh 脚本

    [root@jws-ftp prometheus]# cat /opt/hello.sh
    #!/bin/bash
    while true
    do
        echo hello world >> /tmp/hello.log
        sleep 10
    done
    [root@jws-ftp prometheus]#

        赋予执行权限

    [root@jws-ftp prometheus]# chmod 0755 /opt/hello.sh
    [root@jws-ftp prometheus]#
    [root@jws-ftp prometheus]# ll /opt/hello.sh
    -rwxr-xr-x. 1 root root 85 3月   1 14:04 /opt/hello.sh
    [root@jws-ftp prometheus]#
    

    2、在/etc/systemd/system/ 下创建Unit定义文件

    [root@jws-ftp prometheus]# cat /etc/systemd/system/hello.service
    [Unit]
    Description = hello
    
    [Service]
    ExecStart = /bin/bash /opt/hello.sh
    Restart = always
    Type = simple
    
    [Install]
    WantedBy = multi-user.target
    [root@jws-ftp prometheus]#

    ExecStart中填写想要执行的脚本

    Restart = always 是指进程或服务意外故障的时候可以自动重启的模式。

    ※Unit文件的详细写法会另外给出。

    (Type = simple 指默认的选项没有必要填写,或可理解成其余选项均为系统默认)

    3、把Unit添加进Service

    使用systemctl list-unit-files --type=service命令查看,出现如下图所示即为正常。

    [root@jws-ftp prometheus]# systemctl list-unit-files --type=service | grep hello
    hello.service                                 disabled
    [root@jws-ftp prometheus]#
    

    4、enable服务后使之start

        之后系统将以一般服务的形式处理它

    # 开机自启动on
    [root@jws-ftp prometheus]# systemctl enable hello
    
    # 立即启动
    [root@jws-ftp prometheus]# systemctl start hello

        运行状态确认

    [root@jws-ftp prometheus]# systemctl status hello
    ● hello.service - hello
       Loaded: loaded (/etc/systemd/system/hello.service; enabled; vendor preset: disabled)
       Active: active (running) since 一 2021-03-01 14:12:08 CST; 11min ago
     Main PID: 38133 (bash)
       CGroup: /system.slice/hello.service
               ├─38133 /bin/bash /opt/hello.sh
               └─38272 sleep 10
    
    3月 01 14:12:08 jws-ftp systemd[1]: Started hello.
    3月 01 14:12:08 jws-ftp systemd[1]: Starting hello...
    [root@jws-ftp prometheus]#

        打开日志文件看看脚本是否正常运作

    [root@jws-ftp prometheus]# tailf /tmp/hello.log
    hello world
    hello world
    hello world
    hello world

    5、重启机器,查看服务是否正常自动启动

    [root@jws-ftp prometheus]# reboot

         重启后,如正常显示hello服务即为操作成功

    Systemd的使用指南

    https://www.jianshu.com/p/7fd8b6ea336e

    spring-boot 项目可以配合 启动脚本进行使用

    https://my.oschina.net/zhongwenhao/blog/3064313

  • 相关阅读:
    C++ MFC学习 (二)
    C++ MFC字符转换
    C++ MFC学习 (一)
    Windows.h 文件学习
    Git 学习
    Git 学习
    php压缩文件夹并下载到本地
    接口类型无限级分类
    mysql 共享锁 排它锁
    docker基础命令
  • 原文地址:https://www.cnblogs.com/yizhipanghu/p/14463432.html
Copyright © 2011-2022 走看看