在 Systemd 普及前(RHEL/CentOS 6 及之前),SysV init 腳本配合 chkconfig 是服務開機自啟的標準做法。本文以 IBM DB2、WebSphere Application Server (WAS)、Tivoli Directory Server (TDS) 為例,完整示範 /etc/init.d 標準腳本撰寫、chkconfig 註冊與權限設定流程。
#!/bin/sh
# chkconfig: 2345 99 01
# description: IBM DB2 Database Server
# processname: db2sysc
# 環境變數
DB2_HOME="/home/db2inst1/sqllib"
DB2_OWNER="db2inst1"
LOCK_FILE="/var/lock/subsys/db2"
start() {
echo -n "Starting IBM DB2: "
su - $DB2_OWNER -c "$DB2_HOME/adm/db2start"
touch $LOCK_FILE
echo "OK"
}
stop() {
echo -n "Shutting down IBM DB2: "
su - $DB2_OWNER -c "$DB2_HOME/adm/db2stop force"
rm -f $LOCK_FILE
echo "OK"
}
case "$1" in
start) start ;;
stop) stop ;;
restart) stop; start ;;
status) su - $DB2_OWNER -c "$DB2_HOME/adm/db2pd -" ;;
*) echo "Usage: $0 {start|stop|restart|status}"; exit 1 ;;
esac
exit 0
# chkconfig:
# 範例:2345 99 01
# runlevels: 2、3、4、5(多用戶/圖形模式)啟動
# start_priority: 99(較晚啟動,確保網路/儲存就緒)
# stop_priority: 01(較早關閉,優先釋放資源)
#!/bin/sh
# chkconfig: 2345 99 01
# description: IBM WebSphere & TDS
WAS_PROFILE_TDS="/opt/IBM/WebSphere/AppServer/profiles/AppSrvTds"
WAS_PROFILE_APP="/opt/IBM/WebSphere/AppServer/profiles/AppSrv01"
WAS_PROFILE_ILOG="/opt/IBM/WebSphere/AppServer/profiles/ilog"
TDS_BIN="/opt/ibm/ldap/V6.3/sbin"
start() {
echo "Starting WebSphere & TDS..."
$WAS_PROFILE_TDS/bin/startServer.sh server1
$WAS_PROFILE_APP/bin/startServer.sh server1
$WAS_PROFILE_ILOG/bin/startServer.sh server1
$TDS_BIN/ibmdiradm -l dsrdbm01 -t
$TDS_BIN/ibmslapd -I dsrdbm01
touch /var/lock/subsys/was_tds
}
stop() {
echo "Stopping WebSphere & TDS..."
$WAS_PROFILE_TDS/bin/stopServer.sh server1
$WAS_PROFILE_APP/bin/stopServer.sh server1
$WAS_PROFILE_ILOG/bin/stopServer.sh server1
$TDS_BIN/ibmdiradm -l dsrdbm01 -k
rm -f /var/lock/subsys/was_tds
}
case "$1" in
start) start ;;
stop) stop ;;
restart) stop; start ;;
*) echo "Usage: $0 {start|stop|restart}"; exit 1 ;;
esac
vi /etc/init.d/startDB2、vi /etc/init.d/startWasTdschmod 755 /etc/init.d/startDB2 /etc/init.d/startWasTdschkconfig --add startDB2
chkconfig --add startWasTds
chkconfig --list | grep -E 'startDB2|startWasTds'
輸出應顯示 2:on 3:on 4:on 5:on
service startDB2 start、service startWasTds stop若環境已為 Systemd,建議改寫為 .service 單元檔:
# /etc/systemd/system/db2.service
[Unit]
Description=IBM DB2 Database Server
After=network.target local-fs.target
[Service]
Type=forking
User=db2inst1
Environment=DB2_HOME=/home/db2inst1/sqllib
ExecStart=/home/db2inst1/sqllib/adm/db2start
ExecStop=/home/db2inst1/sqllib/adm/db2stop force
TimeoutSec=300
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl enable db2
systemctl start db2
.bash_profile,務必在腳本內完整設定 PATH、LD_LIBRARY_PATH、DB2_HOME 等。su - $OWNER -c 確保載入用戶環境;避免直接 sudo -u 導致環境變數遺失。/var/lock/subsys/ 是 chkconfig 判斷服務狀態依據,必須 touch/rm 對應檔案。掌握 SysV init 腳本規範與 chkconfig 管理,無論維護舊版系統或理解 Systemd 的演進邏輯,都是 Linux 運維工程師的核心基本功。