centos 7.x編寫開機啓動服務(systemctl start|stop|restart) - (nginx)

centos 7以上是用Systemd進行系統初始化的,Systemd 是 Linux 系統中最新的初始化系統(init),它主要的設計目標是克服 sysvinit 固有的缺點,提高系統的啓動速度。關於Systemd的詳情介紹在這裏。

Systemd服務文件以.service結尾,比如現在要建立nginx爲開機啓動,如果用yum install命令安裝的,yum命令會自動創建nginx.service文件,直接用命令

systemcel enable nginx.service
設置開機啓動即可。
在這裏我是用源碼編譯安裝的,所以要手動創建nginx.service服務文件。
開機沒有登陸情況下就能運行的程序,存在系統服務(system)裏,即:

/lib/systemd/system/

1.在系統服務目錄裏創建nginx.service文件

vim /lib/systemd/system/nginx.service

內容如下

[Unit] 
Description=nginx 
After=network.target 

[Service] 
Type=forking 
ExecStart=/usr/local/nginx/sbin/nginx 
ExecReload=/usr/local/nginx/sbin/nginx -s reload 
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true
[Install] 
WantedBy=multi-user.target

Description:描述服務
After:描述服務類別
[Service]服務運行參數的設置
Type=forking是後臺運行的形式
ExecStart爲服務的具體運行命令
ExecReload爲重啓命令
ExecStop爲停止命令
PrivateTmp=True表示給服務分配獨立的臨時空間
注意:[Service]的啓動、重啓、停止命令全部要求使用絕對路徑
[Install]運行級別下服務安裝的相關設置,可設置爲多用戶,即系統運行級別爲3

保存退出。

2.設置開機啓動

systemctl enable nginx.service

3.其它命令
啓動nginx服務
systemctl start nginx.service
設置開機自啓動
systemctl enable nginx.service
停止開機自啓動
systemctl disable nginx.service
查看服務當前狀態
systemctl status nginx.service
重新啓動服務
systemctl restart nginx.service
查看所有已啓動的服務
systemctl list-units --type=service

4.Systemd 命令和 sysvinit 命令的對照表

Sysvinit 命令 Systemd 命令 備註
service foo start systemctl start foo.service 用來啓動一個服務 (並不會重啓現有的)
service foo stop systemctl stop foo.service 用來停止一個服務 (並不會重啓現有的)。
service foo restart systemctl restart foo.service 用來停止並啓動一個服務。
service foo reload systemctl reload foo.service 當支持時,重新裝載配置文件而不中斷等待操作。
service foo condrestart systemctl condrestart foo.service 如果服務正在運行那麼重啓它。
service foo status systemctl status foo.service 彙報服務是否正在運行。
ls /etc/rc.d/init.d/ systemctl list-unit-files –type=service 用來列出可以啓動或停止的服務列表。
chkconfig foo on systemctl enable foo.service 在下次啓動時或滿足其他觸發條件時設置服務爲啓用
chkconfig foo off systemctl disable foo.service 在下次啓動時或滿足其他觸發條件時設置服務爲禁用
chkconfig foo systemctl is-enabled foo.service 用來檢查一個服務在當前環境下被配置爲啓用還是禁用。
chkconfig –list systemctl list-unit-files –type=service 輸出在各個運行級別下服務的啓用和禁用情況
chkconfig foo –list ls /etc/systemd/system/*.wants/foo.service 用來列出該服務在哪些運行級別下啓用和禁用。
chkconfig foo –add systemctl daemon-reload 當您創建新服務文件或者變更設置時使用。
telinit 3 systemctl isolate multi-user.target (ORsystemctl isolate runlevel3.target OR telinit 3) 改變至多用戶運行級別。

5.Sysvinit 運行級別和 systemd 目標的對應表

Sysvinit 運行級別 Systemd 目標 備註
0 runlevel0.target, poweroff.target 關閉系統。
1, s, single runlevel1.target, rescue.target 單用戶模式。
2, 4 runlevel2.target, runlevel4.target, multi-user.target 用戶定義/域特定運行級別。默認等同於 3。
3 runlevel3.target, multi-user.target 多用戶,非圖形化。用戶可以通過多個控制檯或網絡登錄。
5 runlevel5.target, graphical.target 多用戶,圖形化。通常爲所有運行級別 3 的服務外加圖形化登錄。
6 runlevel6.target, reboot.target 重啓
emergency emergency.target 緊急 Shell

原文地址:http://www.dohooe.com/2016/03/03/352.html?utm_source=tuicool&utm_medium=referral

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