Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 開機自動啟動腳本配置完整指南:chkconfig 與 systemd 實戰

編輯:Linux 教學

SysV init 傳統方式 (CentOS 6 / RHEL 6)

步驟 1:建立啟動腳本

cd /etc/init.d
vim myservice.sh

腳本模板 (含 chkconfig 標註)

#!/bin/bash
# chkconfig: 2345 70 30
# description: My custom service description
# processname: myservice

# 必須:載入環境變數 (系統啟動時尚未載入 /etc/profile)
source /etc/profile

start() {
    echo "Starting myservice..."
    /usr/local/bin/myservice --daemon
}

stop() {
    echo "Stopping myservice..."
    killproc myservice
}

case "$1" in
    start) start ;;
    stop) stop ;;
    restart) stop; start ;;
    status) status myservice ;;
    *) echo "Usage: $0 {start|stop|restart|status}" ;;
esac

chkconfig 註解解析

# chkconfig: 2345 70 30
# 2345  : 運行等級 2,3,4,5 啟動 (3=多用戶文字, 5=圖形介面)
# 70    : 啟動順序號 (數字越小越早啟動,依賴服務需更小)
# 30    : 關機停止順序號 (數字越小越早停止)

部署步驟

chmod +x /etc/init.d/myservice.sh
chkconfig --add myservice
chkconfig myservice on

# 驗證
chkconfig --list myservice
# myservice  0:off  1:off  2:on  3:on  4:on  5:on  6:off

Systemd 現代方式 (CentOS 7+ / RHEL 7+)

建立服務單元檔

vim /etc/systemd/system/myservice.service
[Unit]
Description=My Custom Service
After=network.target
Wants=network.target

[Service]
Type=simple
EnvironmentFile=-/etc/sysconfig/myservice
ExecStart=/usr/local/bin/myservice --daemon
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=myservice

[Install]
WantedBy=multi-user.target

部署與管理

systemctl daemon-reload
systemctl enable myservice
systemctl start myservice
systemctl status myservice

# 開機自啟
systemctl enable myservice

# 查看日誌
journalctl -u myservice -f

環境變數載入關鍵

SysV init 腳本中 必須 手動 source /etc/profile,因為啟動時環境變數尚未載入。Systemd 透過 EnvironmentFile 或 Environment= 顯式宣告。

常用管理指令對照

功能SysV initSystemd
啟動service myservice startsystemctl start myservice
停止service myservice stopsystemctl stop myservice
重啟service myservice restartsystemctl restart myservice
狀態service myservice statussystemctl status myservice
啟用開機自啟chkconfig myservice onsystemctl enable myservice
停用開機自啟chkconfig myservice offsystemctl disable myservice
查看狀態chkconfig --listsystemctl list-unit-files
Copyright © Windows教程網 All Rights Reserved