macOS 安裝 PostgreSQL 的流程
以下是安裝 PostgreSQL 以及基本使用的完整流程與注意事項。
1. 安裝 PostgreSQL
使用 Homebrew 安裝指定版本的 PostgreSQL:
brew install postgresql@17
確認安裝路徑:
brew --prefix postgresql
# 範例輸出:/usr/local/opt/postgresql@17
將 PostgreSQL 的執行檔加入環境變數:
export PATH="/usr/local/opt/postgresql@17/bin:$PATH" >> ~/.zshrc
source ~/.zshrc
確認安裝是否成功:
psql --version
2. 啟動 PostgreSQL 服務
啟動 PostgreSQL:
brew services start postgresql@17
若啟動失敗,可能需要初始化資料庫:
initdb -D /usr/local/var/postgresql@17
brew services restart postgresql@17
檢查 PostgreSQL 狀態:
pg_ctl -D /usr/local/var/postgresql@17 status
3. 建立使用者與資料庫
建立預設的 postgres
使用者與資料庫:
createuser -s postgres
createdb -U postgres postgres
4. 使用 psql 連線到資料庫
連線到 PostgreSQL:
psql -h localhost -U postgres -d postgres
進入 psql 後,建立新的資料庫:
CREATE DATABASE testdb;
切換到新建立的資料庫:
\c testdb
建立資料表範例:
CREATE TABLE user (
id UUID PRIMARY KEY,
name TEXT,
birthday DATE
);
5. 檢查 PostgreSQL 狀態的自動化腳本
建立一個檢查 PostgreSQL 狀態的腳本 check_postgres.sh
:
#!/bin/bash
PGDATA="/usr/local/var/postgresql@17"
echo "🔍 Checking PostgreSQL status..."
pg_ctl -D "$PGDATA" status
if [ $? -ne 0 ]; then
echo "🚀 PostgreSQL not running, attempting to start..."
pg_ctl -D "$PGDATA" start
else
echo "✅ PostgreSQL already running."
fi
echo "🌐 Checking port 5432..."
lsof -iTCP:5432 -sTCP:LISTEN || echo "❌ Not listening on port 5432"
echo "📋 Existing databases:"
psql -l || echo "⚠️ psql failed. Is PostgreSQL running?"
執行腳本檢查 PostgreSQL 狀態:
bash check_postgres.sh
6. 常見問題與解決方法
問題 1:psql: 錯誤: role "postgres" does not exist
解決方法:
- 使用
createuser -s postgres
建立postgres
使用者。
問題 2:啟動 PostgreSQL 時出現 Bootstrap failed: 5: Input/output error
解決方法:
- 刪除舊的啟動檔案並重新啟動服務:
rm ~/Library/LaunchAgents/homebrew.mxcl.postgresql@17.plist brew services cleanup brew services start postgresql@17
7. 注意事項
- 版本管理:安裝多個版本的 PostgreSQL 時,需確認環境變數是否正確指向目標版本。
- 資料庫初始化:若安裝後無法啟動,可能需要手動執行
initdb
初始化資料庫。 - 權限問題:確保使用者擁有足夠的權限來操作資料庫。
- 服務管理:使用
brew services
管理 PostgreSQL 的啟動與停止。