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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM