Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux教程

systemd 指令全攻略:用 systemctl 管理你的 Linux 系統

systemd 是新世代的 Linux 服務管理器,取代了傳統的 init 系統。它負責系統開機流程,一旦啟動就監管整個系統。本文以 CentOS 7.0(systemd 216)為例,整理最常用到的操作。

它之所以被迅速採用,一個關鍵原因是:PID 1 已由 systemd 佔據,這可以透過 pstree 直接看到。

開機更快的原因

sysvinit 是序列地一個接一個啟動服務,systemd 則是平行啟動,而且只先拉起確實被依賴的服務,大幅縮短開機時間。

systemd-analyze               # 總開機耗时
systemd-analyze time          # 同上
systemd-analyze blame         # 依初始化耗時排序所有 unit

blame 的輸出很長,可用方向鍵捲動,找出拖慢開機的元凶。

systemctl:查詢狀態

systemctl                     # 列出所有正在運行的 unit
systemctl list-units
systemctl --failed            # 只列出失敗的 unit

服務管理

systemctl list-units -t service       # 列出所有已啟用的服務
systemctl status dnsmasq              # 查看服務狀態
systemctl start dnsmasq               # 啟動
systemctl stop dnsmasq                # 停止
systemctl restart dnsmasq             # 重啟
systemctl reload sshd                 # 不重啟服務而重新載入設定

官方文件建議使用帶 .service 的完整名稱寫法,例如 systemctl status dnsmasq.service,這在撰寫腳本時能避免歧義。

開機自啟與其他常用操作

systemctl enable sshd           # 設為開機自啟
systemctl disable sshd          # 取消自啟
systemctl is-enabled sshd       # 查詢是否自啟
systemctl mask nginx            # 徹底鎖住某服務,禁止手動啟動
journalctl -u nginx -f          # 即時查看該服務日誌
systemctl list-dependencies     # 查看 unit 之間的依賴關係

從 service 與 chkconfig 遷移過來的人,只要記住「start / stop / restart / status / enable / disable」這六個動詞,絕大多數日常工作都能應付。遇到服務起不來時,systemctl status 加上 journalctl -u 幾乎總能找到線索。

Copyright © Linux教程網 All Rights Reserved