Skip to main content

PostgreSQL Configs

info

PostgreSQL 配置文档

基于 Homebrew 安装 PostgreSQL


# 0) 安装
brew install postgresql@14

# 1) 配置 PATH(两处都加,保证 login shell 和交互 shell 都生效)
# - zprofile 适用于登录/新开终端(macOS 默认)
# - zshrc 适用于交互式 shell(如 VS Code 的内置终端)
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zshrc
echo 'export PATH="$(brew --prefix)/opt/postgresql@14/bin:$PATH"' >> ~/.zprofile
echo 'export PATH="$(brew --prefix)/opt/postgresql@14/bin:$PATH"' >> ~/.zshrc
# 让当前会话立刻生效
source ~/.zprofile || true
source ~/.zshrc || true

# 2) 变量(自动适配 Intel/ARM 的 Homebrew 前缀)
PG_PREFIX="$(brew --prefix)"
PG_BIN="$PG_PREFIX/opt/postgresql@14/bin"
DATA_DIR="$PG_PREFIX/var/postgresql@14"

# 3) 初始化数据目录(第一次装才需要;已有 PG_VERSION 就跳过)
# 会提示你为超级用户 postgres 设置密码
if [ ! -f "$DATA_DIR/PG_VERSION" ]; then
mkdir -p "$DATA_DIR"
"$PG_BIN/initdb" -D "$DATA_DIR" -U postgres -A scram-sha-256 -W
fi

# 4) 启动服务(用 brew 的 LaunchAgent 托管)
brew services start postgresql@14

# 5) 连通性自检(端口监听 + 用 TCP 直连,避开 /tmp socket 问题)
lsof -nP -iTCP:5432 -sTCP:LISTEN
psql -h 127.0.0.1 -p 5432 -U postgres -d postgres -c "SELECT version();"

常用命令

# 启动之后查询当前用户 - 尝试用你的 macOS 用户名登录
psql -h 127.0.0.1 -p 5432 -U "$(whoami)" -d postgres -c "\du"

# 创建 DB超级用户
# username: postgres, password: postgres
psql -d postgres -c "CREATE ROLE postgres WITH LOGIN SUPERUSER PASSWORD 'postgres';"

# 停止服务
brew services stop postgresql@14

# 重启服务
brew services restart postgresql@14

# 查看服务状态
brew services list | grep postgresql


# 如果我启动了一个docker容器 docker run -p 5432:5432 ...
# 但是你本机的 Postgres 已经占着 5432

#方案1: 先停本机 PG,再用 5432:5432
#方案2 本机留着 5432 给“本地 PG”,容器映射到 5433