systemd科普 創建 nginx service

systemd:

    CentOS 7的服務systemctl腳本存放在:/usr/lib/systemd/,有系統(system)和用戶(user)之分,即:/usr/lib/systemd/system ,/usr/lib/systemd/user

    每一個服務以.service結尾,一般會分爲3部分:[Unit]、[Service]和[Install],就以nginx爲例吧,具體內容如下:

創建service:

在/usr/lib/systemd/system下創建nginx.service文件內容如下(看應用需求也可以在 /usr/lib/systemd/usr下創建):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
  
[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx-t -c /etc/nginx/nginx.conf
ExecStart=/usr/sbin/nginx-c/etc/nginx/nginx.conf
ExecReload=/bin/kill-s HUP $MAINPID
ExecStop=/bin/kill-s QUIT $MAINPID
PrivateTmp=true
  
[Install]
WantedBy=multi-user.target

[Unit]

Description : 服務的簡單描述
Documentation : 服務文檔

After= : 依賴,僅當依賴的服務啓動之後再啓動自定義的服務單元

[Service]

Type : 啓動類型simple、forking、oneshot、notify、dbus

Type=simple(默認值):systemd認爲該服務將立即啓動。服務進程不會fork。如果該服務要啓動其他服務,不要使用此類型啓動,除非該服務是socket激活型。 
Type=forking:systemd認爲當該服務進程fork,且父進程退出後服務啓動成功。對於常規的守護進程(daemon),除非你確定此啓動方式無法滿足需求,使用此類型啓動即可。使用此啓動類型應同時指定 PIDFile=,以便systemd能夠跟蹤服務的主進程。
 Type=oneshot:這一選項適用於只執行一項任務、隨後立即退出的服務。可能需要同時設置 RemainAfterExit=yes 使得 systemd 在服務進程退出之後仍然認爲服務處於激活狀態。 
Type=notify:與 Type=simple 相同,但約定服務會在就緒後向 systemd 發送一個信號。這一通知的實現由 libsystemd-daemon.so 提供。 Type=dbus:若以此方式啓動,當指定的 BusName 出現在DBus系統總線上時,systemd認爲服務就緒。

PIDFile : pid文件路徑 
ExecStartPre :啓動前要做什麼,上文中是測試配置文件 -t  
ExecStart:啓動 
ExecReload:重載 
ExecStop:停止 

PrivateTmp:True表示給服務分配獨立的臨時空間

[Install]

WantedBy:服務安裝的用戶模式,從字面上看,就是想要使用這個服務的有是誰?上文中使用的是:multi-user.target ,就是指想要使用這個服務的目錄是多用戶。「以上全是個人理解,瞎猜的,如有不當,請大家多多指教每一個.target實際上是鏈接到我們單位文件的集合,當我們執行:

?
1
$sudo systemctl enable nginx.service

就會在/etc/systemd/system/multi-user.target.wants/目錄下新建一個/usr/lib/systemd/system/nginx.service 文件的鏈接。

操作Service:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#啓動服務
$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.conftestis 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



systemd科普

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章