萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 開機自啟動配置全攻略:從 chkconfig 到 systemd 完整解析

服務管理基礎:chkconfig 指令

查看服務啟動狀態

chkconfig --list
# 輸出範例:
# openvpn  0:關閉  1:開啟  2:開啟  3:開啟  4:開啟  5:開啟  6:關閉

修改服務啟動等級

# 語法:chkconfig --level <等級> <服務名> on/off
chkconfig --level 35 openvpn on   # 運行等級 3,5 啟用
chkconfig --level 5 openvpn off   # 運行等級 5 停用

使用者層級自啟動配置

方法一:~/.bash_profile(登入 Shell 執行)

echo "synergyc 192.168.0.154" >> ~/.bash_profile

限制:需用戶登入後才執行,不適用於無人值守伺服器。

系統層級自啟動傳統機制(SysV init)

核心目錄結構

  • /etc/init.d/:所有服務啟動腳本實體
  • /etc/rc.d/rc<0-6>.d/:各運行等級的啟動/停止符號連結

建立自訂服務腳本範例

# 1. 建立腳本 /etc/init.d/myservice
cat > /etc/init.d/myservice << 'EOF'
#!/bin/bash
# chkconfig: 345 90 10
# description: My custom service

RESTART="/usr/local/bin/myapp restart"
START="/usr/local/bin/myapp start"
STOP="/usr/local/bin/myapp stop"

case "$1" in
    start)
        $START
        echo "Service started"
        ;;
    stop)
        $STOP
        echo "Service stopped"
        ;;
    restart)
        $RESTART
        echo "Service restarted"
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac
EOF

# 2. 賦予執行權限
chmod +x /etc/init.d/myservice

# 3. 註冊到運行等級
chkconfig --add myservice
chkconfig --level 345 myservice on

連結命名規則

  • S##name:啟動連結(Start),數字越小越早啟動
  • K##name:停止連結(Kill),數字越小越早停止

Debian/Ubuntu 系統:update-rc.d 工具

基本用法

# 預設優先順序註冊
update-rc.d myscript defaults

# 自訂啟動/停止順序與等級
update-rc.d myscript start 90 2 3 4 5 . stop 10 0 1 6 .

# 移除所有連結
update-rc.d -f myscript remove

參數解析

start 90 2 3 4 5 .
# 在等級 2,3,4,5 以順序 90 啟動

stop 10 0 1 6 .
# 在等級 0,1,6 以順序 10 停止

現代系統:systemd 服務單元(CentOS 7+/Ubuntu 16.04+)

# 1. 建立服務單元 /etc/systemd/system/myservice.service
[Unit]
Description=My Custom Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/myapp
Restart=on-failure
User=nobody

[Install]
WantedBy=multi-user.target

# 2. 重載 systemd、啟用並啟動
systemctl daemon-reload
systemctl enable myservice
systemctl start myservice

# 3. 狀態查看
systemctl status myservice

定時任務替代方案

類型工具適用場景
週期性crontab定時備份、日誌輪轉、定期同步
單次延遲at一次性維護、臨時任務
開機單次@reboot (cron)啟動後延遲執行

crontab 範例

# 每天 03:00 執行備份
0 3 * * * /scripts/backup.sh

# 每月 1 號 02:00 清理舊日誌
0 2 1 * * find /var/log -name "*.log" -mtime +30 -delete

at 單次任務

# 互動模式
at 14:30
at> /scripts/maintenance.sh
at> Ctrl+D

# 檔案模式
at -f /scripts/task.sh 23:59
copyright © 萬盛學電腦網 all rights reserved