Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

CentOS 6.5 Tomcat 開機自啟動失效?環境變數缺失是主因

編輯:Linux 系統常見問題解答

問題現象

CentOS 6.5 上配置 Tomcat 開機自啟動,將 `startup.sh` 或 `catalina.sh start` 直接加入 `/etc/rc.local`,重啟後 Tomcat 未啟動。

根因分析

`rc.local` 執行環境**極度精簡**:無 `JAVA_HOME`、`PATH`、`CLASSPATH`、`CATALINA_HOME` 等關鍵環境變數,導致啟動腳本找不到 java、tomcat 相關類庫而靜默失敗。

解決方案:包裝啟動腳本注入環境變數

1. 建立自啟動腳本

vim /usr/local/apache-tomcat-7.0.53/bin/auto-startup.sh

內容:

#!/bin/bash
export JAVA_HOME=/usr/local/jdk1.7.0_51
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export CATALINA_HOME=/usr/local/apache-tomcat-7.0.53

$CATALINA_HOME/bin/catalina.sh start

2. 賦予執行權限並掛載

chmod +x /usr/local/apache-tomcat-7.0.53/bin/auto-startup.sh
echo "/usr/local/apache-tomcat-7.0.53/bin/auto-startup.sh" >> /etc/rc.local

3. 驗證

reboot
ps -ef | grep tomcat
# 應看到 Bootstrap start 進程

關鍵點總結

  • **環境變數必須在腳本內部 export**,rc.local 不會載入 `/etc/profile` 或使用者 `.bash_profile`。
  • 路徑請改為實際安裝路徑(JDK、Tomcat)。
  • CentOS 7+ 建議改用 **systemd Unit** 管理,更標準、支援依賴順序、日誌整合。

systemd 版範例(CentOS 7+)

# /etc/systemd/system/tomcat.service
[Unit]
Description=Apache Tomcat
After=network.target

[Service]
Type=forking
Environment=JAVA_HOME=/usr/local/jdk1.8.0_202
Environment=CATALINA_HOME=/usr/local/apache-tomcat-8.5.50
Environment=CATALINA_BASE=/usr/local/apache-tomcat-8.5.50
ExecStart=$CATALINA_HOME/bin/startup.sh
ExecStop=$CATALINA_HOME/bin/shutdown.sh
User=tomcat
Group=tomcat

[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl enable tomcat
systemctl start tomcat

結語

開機自啟動失敗 90% 是環境變數缺失。將完整環境封裝在啟動腳本或 systemd Unit 中,是穩健部署的關鍵。

Copyright © Windows教程網 All Rights Reserved