执行rails db:setup时PostgreSQL无密码认证失败问题求助
解决Rails执行
rails db:setup时的PostgreSQL连接认证错误 问题描述
执行rails db:setup命令时触发ActiveRecord::ConnectionNotEstablished错误,具体提示:
connection to server at "localhost" (::1), port 5432 failed: fe_sendauth: no password supplied Couldn't create 'reservify_back_end_development' database. Please check your configuration. rails aborted! ActiveRecord::ConnectionNotEstablished: connection to server at "localhost" (::1), port 5432 failed: fe_sendauth: no password supplied
当前config/database.yml的核心配置片段:
default: &default adapter: postgresql encoding: unicode pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> development: <<: *default database: reservify_back_end_development #username: reservify_back_end #password: #host: localhost #port: 5432
解决办法
方法1:在database.yml中配置PostgreSQL认证信息
打开config/database.yml,取消development段中username和password的注释,填写你的PostgreSQL用户(通常默认是postgres)的用户名和密码:
development: <<: *default database: reservify_back_end_development username: postgres # 替换为你的PostgreSQL用户名 password: your_postgres_password # 替换为你的PostgreSQL密码
保存文件后,重新执行rails db:setup。
方法2:修改PostgreSQL配置信任本地连接(仅开发环境推荐)
- 找到PostgreSQL的
pg_hba.conf配置文件:- macOS(Homebrew安装):
/usr/local/var/postgres/pg_hba.conf或/opt/homebrew/var/postgres/pg_hba.conf - Linux:
/etc/postgresql/[你的PostgreSQL版本]/main/pg_hba.conf - Windows:
C:\Program Files\PostgreSQL\[你的PostgreSQL版本]\data\pg_hba.conf
- macOS(Homebrew安装):
- 找到IPv4和IPv6本地连接的配置行,将认证方式从
scram-sha-256或md5改为trust:# 修改前 host all all 127.0.0.1/32 scram-sha-256 host all all ::1/128 scram-sha-256 # 修改后 host all all 127.0.0.1/32 trust host all all ::1/128 trust - 重启PostgreSQL服务:
- macOS:
brew services restart postgresql - Linux:
sudo systemctl restart postgresql - Windows:打开服务管理器,找到PostgreSQL服务并重启
- macOS:
- 重新执行
rails db:setup。
方法3:使用环境变量传递数据库认证信息(更安全)
通过环境变量DATABASE_URL传递完整的数据库连接信息,避免在配置文件中明文存储密码:
- 终端临时设置:
export DATABASE_URL="postgres://postgres:your_password@localhost/reservify_back_end_development" - 若要永久生效,可将上述命令添加到你的shell配置文件(如
.bashrc、.zshrc)中。
设置完成后执行rails db:setup即可。
内容的提问来源于stack exchange,提问作者Hamza
相关产品推荐
相关产品推荐

