pg_ctl 是 PostgreSQL 官方提供的服務控制工具,用於管理 postmaster 後端進程。以下是常用操作模式的標準語法:
pg_ctl start [-w] [-s] [-D datadir] [-l filename] [-o options] [-p path]
pg_ctl stop [-W] [-s] [-D datadir] [-m s[mart] | f[ast] | i[mmediate]]
pg_ctl restart [-w] [-s] [-D datadir] [-m s[mart] | f[ast] | i[mmediate]] [-o options]
pg_ctl reload [-s] [-D datadir]
pg_ctl status [-D datadir]
pg_ctl kill [signal_name] [process_id]
在後台啟動新的資料庫伺服器。標準輸入導向 /dev/null,若指定 -l 參數,標準輸出與錯誤將寫入日誌檔案;否則輸出導向 pg_ctl 的標準輸出。建議搭配日誌輪轉工具(如 rotatelogs)使用,避免輸出佔用控制終端導致進程無法正確脫離 shell 進程組。
關閉指定資料目錄下的伺服器,支援三種關閉策略:
相當於先執行 stop 再執行 start,但會保留並重用上一次 postmaster 的命令列參數,方便修改啟動選項後生效。
向 postmaster 發送 SIGHUP 訊號,使其重新讀取 postgresql.conf、pg_hba.conf 等設定檔,無需完整重啟即可套用新設定。
檢查指定資料目錄是否有伺服器正在運行,若有則顯示其 PID 與啟動命令列參數。
向指定進程發送訊號,在缺乏原生 kill 命令的 Windows 環境下特別有用。
| 參數 | 說明 |
|---|---|
-D datadir | 指定資料庫檔案系統位置,省略時使用環境變數 PGDATA |
-l filename | 將伺服器日誌附加至指定檔案,檔案不存在時自動建立,權限預設 077 |
-m mode | 指定關閉模式:smart、fast、immediate 或其首字母 |
-o options | 直接傳遞給 postmaster 的選項,建議用單雙引號包裹 |
-p path | 指定 postmaster 執行檔位置,通常無需設定 |
-s | 僅輸出錯誤訊息,抑制提示資訊 |
-w | 等待啟動/關閉完成(最長 60 秒),關閉時為預設行為 |
-W | 不等待完成,啟動與重啟時為預設行為 |
$ pg_ctl start
$ pg_ctl -w start # 等待啟動完成
$ pg_ctl -o "-F -p 5433" start # 指定埠 5433 並關閉 fsync
$ pg_ctl stop
$ pg_ctl -w -m fast stop # 等待快速關閉完成
$ pg_ctl restart
$ pg_ctl -w restart # 等待重啟完成
$ pg_ctl -o "-F -p 5433" restart # 變更埠號並重啟
$ pg_ctl status
pg_ctl: postmaster is running (pid: 13718)
Command line was:
/usr/local/pgsql/bin/postmaster '-D' '/usr/local/pgsql/data' '-p' '5433' '-B' '128'
等待完全啟動並非嚴格定義的操作,若存取控制要求本地用戶端需手動互動(如密碼認證),可能導致等待超時。生產環境建議搭配 systemd 或 init 系統管理服務,而非直接依賴 pg_ctl。