使用HomeBrew安装Postgres后,psql登录postgres用户需密码的问题
Hey there, let's break down why you're hitting this password prompt issue and how to fix it—Homebrew's PostgreSQL setup on macOS has some quirks compared to other installs.
Why sudo -u postgres psql asks for a password?
The key thing to know: Homebrew doesn't create a system-level postgres user on macOS. Instead, it sets your current system user (the one you used to install Homebrew/PostgreSQL) as the superuser for PostgreSQL (matching the postgres database role).
That password prompt you're seeing is likely your system's sudo password (your current user's admin password), not a PostgreSQL password. Even if you enter it, you might still fail to log in because the postgres system user probably doesn't exist on your Mac—Homebrew never created it.
The correct way to log in
Skip the sudo stuff entirely. Just run this in your terminal:
psql
This logs you in directly as your system user, which is already the PostgreSQL superuser. No password required, since Homebrew defaults to trust-based authentication for local users.
If you need to use the postgres role specifically
If you want to operate as the postgres database role (not the system user), you can either:
- Log in first with
psql, then run this SQL command:SET ROLE postgres; - Or log in directly with:
psql -U postgres
Since your system user is a superuser, you won't need a password for this.
Fixing your pg_hba.conf changes
Your pg_hba.conf config looks correct (setting all local connections to trust), but changes to this file only take effect after restarting PostgreSQL. Run this to restart the service:
brew services restart postgresql
Double-check you edited the right file too—Homebrew's PostgreSQL config lives at:
- Intel Macs:
/usr/local/var/postgres/pg_hba.conf - Apple Silicon Macs:
/opt/homebrew/var/postgres/pg_hba.conf
Creating a new user and database
Once you're logged in, here's how to set up your new user and database:
- Create a user (replace
myuserandmypasswordwith your details):CREATE USER myuser WITH PASSWORD 'mypassword'; - Create a database owned by that user:
CREATE DATABASE mydb OWNER myuser; - Grant full privileges to the user on the database (if needed):
GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser; - Exit psql with:
\q
Why your current system user password didn't work?
Homebrew's default setup lets your system user log in without a password. If you were prompted for one, it's probably because your pg_hba.conf changes weren't applied (you didn't restart the service) or you modified the auth settings earlier. Restarting PostgreSQL and using the plain psql command should fix this.
内容的提问来源于stack exchange,提问作者Gábor Pintér

