在 macOS 環境下安裝 MySQL 後,若希望資料庫服務能隨著系統開機自動啟動,最標準的做法是建立一個 launchd 的設定檔(Plist)。以下將詳細說明建立檔案、編寫內容與載入服務的完整步驟。
首先打開終端機,使用 touch 指令在 /Library/LaunchDaemons/ 目錄下建立一個屬於 MySQL 的啟動項目檔案。這個目錄下的服務會在系統啟動階段、以 root 權限執行,非常適合資料庫這類核心服務。
sudo touch /Library/LaunchDaemons/com.mysql.mysql.plist
使用文字編輯器(如 vim、nano 或 GUI 編輯器)打開剛建立的檔案,貼入下列 XML 內容。請注意 ProgramArguments 中的執行檔路徑 /usr/local/mysql/bin/mysqld_safe 需符合實際安裝位置;若你是透過 Homebrew 安裝,路徑可能為 /opt/homebrew/bin/mysqld_safe(Apple Silicon)或 /usr/local/bin/mysqld_safe(Intel),請依實際情況調整。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.mysql.mysqld</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/mysql/bin/mysqld_safe</string>
<string>--user=root</string>
</array>
</dict>
</plist>
關鍵參數說明:
KeepAlive:設為 true,若進程意外終止,launchd 會自動重啟它。Label:服務的唯一識別碼,慣用反向網域名稱格式。ProgramArguments:啟動命令與參數陣列,第一項為執行檔完整路徑,後續為傳遞參數。存檔後,執行下列指令將服務載入 launchd 並設定開機自動啟動(-w 參數會將狀態寫入覆寫檔,確保重開機後依然生效):
sudo launchctl load -w /Library/LaunchDaemons/com.mysql.mysql.plist
輸入 sudo launchctl list | grep mysql 若看到服務狀態為運行中,即設定成功。若啟動失敗,請檢查:
644(sudo chmod 644 /Library/LaunchDaemons/com.mysql.mysql.plist)。which mysqld_safe 確認)。/var/log/system.log 或執行 sudo launchctl debug system/com.mysql.mysqld --stdout --stderr 除錯。完成以上步驟,MySQL 便能在 macOS 開機時自動啟動,無需手動介入。