跳至主要内容

[PSQL] Getting Started

PostgreSQL Tutorial

安裝

# 透過 homebrew 安裝
$ brew install postgresql
$ brew services start postgresql
$ psql postgres

透過 Docker Compose 啟動

services:
postgres:
image: postgres:17
container_name: postgres
restart: unless-stopped
ports:
- "5432:5432"
environment:
POSTGRES_USER: ${POSTGRES_USER:-postgres}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
POSTGRES_DB: ${POSTGRES_DB:-postgres}
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: [ "CMD-SHELL", "pg_isready -U postgres" ]
interval: 5s
timeout: 5s
retries: 5

volumes:
pgdata:
  • ${POSTGRES_USER:-postgres} 表示若有設定環境變數就用該值,否則預設為 postgres
  • volumes 使用 named volume pgdata 讓資料在 container 重啟後仍然保留
  • healthcheckpg_isready 確認 PostgreSQL 已就緒

啟動後,可以透過以下指令連進 container 內的 psql:

docker exec -it postgres psql -U postgres

錯誤處理

突然連不上 db,重新安裝 postgres 的方式:Completely Uninstall and Reinstall PSQL on OSX

# https://medium.com/@bitadj/completely-uninstall-and-reinstall-psql-on-osx-551390904b86

# Make sure brew is happy
$ brew doctor
$ brew update

# Uninstall PostgreSQL using Homebrew
$ brew uninstall postgresql

# Remove all local PostgreSQL files
$ rm -rf /usr/local/var/postgres
$ rm -rf .psql_history .psqlrc .psql.local .pgpass .psqlrc.local

# Confirm that PostgreSQL is actually uninstalled
$ brew list

# reinstall postgres
$ brew update
$ brew install postgres
$ brew services start postgresql