linux service腳本


vim /etc/systemd/system/node_exporter.service

[Unit]
Description=node_exporter
Documentation=https://prometheus.io/
After=network.target
[Service]
Type=simple
User=prometheus
ExecStart=/usr/local/bin/node_exporter
Restart=on-failure
[Install]
WantedBy=multi-user.target

 

1.服務權限
systemd有系統和用戶區分;系統(/user/lib/systemd/system/)、用戶(/etc/lib/systemd/user/).

一般系統管理員手工創建的單元文件建議存放在/etc/systemd/system/目錄下面。

2.命令說明

[Unit]區塊通常是配置文件的第一個區塊,用來定義 Unit(在這里就是服務) 的元數據,以及配置與其他 Unit 的關系。它的主要字段如下。

Description:簡短描述
Documentation:文檔地址
Requires:當前 Unit 依賴的其他 Unit,如果它們沒有運行,當前 Unit 會啟動失敗
Wants:與當前 Unit 配合的其他 Unit,如果它們沒有運行,當前 Unit 不會啟動失敗
BindsTo:與Requires類似,它指定的 Unit 如果退出,會導致當前 Unit 停止運行
Before:如果該字段指定的 Unit 也要啟動,那么必須在當前 Unit 之后啟動
After:如果該字段指定的 Unit 也要啟動,那么必須在當前 Unit 之前啟動
Conflicts:這里指定的 Unit 不能與當前 Unit 同時運行
Condition...:當前 Unit 運行必須滿足的條件,否則不會運行
Assert...:當前 Unit 運行必須滿足的條件,否則會報啟動失敗

[Service]區塊用來 Service 的配置,只有 Service 類型的 Unit 才有這個區塊。它的主要字段如下。

Type:定義啟動時的進程行為。它有以下幾種值。
Type=simple:默認值,執行ExecStart指定的命令,啟動主進程
Type=forking:如果使用了這個Type,則ExecStart的腳本啟動后會調用fork()函數創建一個進程作為其啟動的一部分。當一切初始化完畢后,父進程會退出。子進程會繼續作為主進程執行。這是傳統UNIX主進程的行為。如果這個設置被指定,建議同時設置PIDFile選項來指定pid文件的路徑,以便systemd能夠識別主進程
Type=oneshot:一次性進程,Systemd 會等當前服務退出,再繼續往下執行
Type=dbus:當前服務通過D-Bus啟動
Type=notify:當前服務啟動完畢,會通知Systemd,再繼續往下執行
Type=idle:若有其他任務執行完畢,當前服務才會運行
ExecStart:啟動當前服務的命令
ExecStartPre:啟動當前服務之前執行的命令
ExecStartPost:啟動當前服務之后執行的命令
ExecReload:重啟當前服務時執行的命令
ExecStop:停止當前服務時執行的命令
ExecStopPost:停止當其服務之后執行的命令
RestartSec:自動重啟當前服務間隔的秒數
Restart:定義何種情況 Systemd 會自動重啟當前服務,可能的值包括always(總是重啟)、on-success、on-failure、on-abnormal、on-abort、on-watchdog
TimeoutSec:定義 Systemd 停止當前服務之前等待的秒數
Environment:指定環境變量

[Install]通常是配置文件的最后一個區塊,用來定義如何啟動,以及是否開機啟動。它的主要字段如下。

 

WantedBy:它的值是一個或多個 Target,當前 Unit 激活時(enable)符號鏈接會放入/etc/systemd/system目錄下面以 Target 名 + .wants后綴構成的子目錄中
RequiredBy:它的值是一個或多個 Target,當前 Unit 激活時,符號鏈接會放入/etc/systemd/system目錄下面以 Target 名 + .required后綴構成的子目錄中
Alias:當前 Unit 可用於啟動的別名
Also:當前 Unit 激活(enable)時,會被同時激活的其他 Unit

 

3.重載服務
systemctl enable nginx.service
就會在/etc/systemd/system/multi-user.target.wants/目錄下新建一個/usr/lib/systemd/system/nginx.service 文件的鏈接。想對應,可以用 disable 把它從 wants 目錄給刪除。

 

4.操作服務
#啟動服務
$ sudo systemctl start nginx.service

#查看日志
$ sudo journalctl -f -u nginx.service
— Logs begin at 四 2015-06-25 17:32:20 CST. —
6月 25 10:28:24 Leco.lan systemd[1]: Starting nginx – high performance web server…
6月 25 10:28:24 Leco.lan nginx[7976]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
6月 25 10:28:24 Leco.lan nginx[7976]: nginx: configuration file /etc/nginx/nginx.conf test is successful
6月 25 10:28:24 Leco.lan systemd[1]: Started nginx – high performance web server.

#重啟
$ sudo systemctl restart nginx.service

#重載
$ sudo systemctl reload nginx.service

#停止
$ sudo systemctl stop nginx.service


免責聲明!

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



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