You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails应用创建PostgreSQL数据库时遇连接拒绝错误求助

解决Rails连接PostgreSQL时的"Connection refused"问题

1. 确认PostgreSQL服务处于运行状态

根据操作系统执行对应命令检查并启动服务:

  • macOS(Homebrew安装):
    • 检查状态:brew services list,查看postgresql状态是否为started
    • 启动服务:brew services start postgresql
  • Linux(Debian/Ubuntu):
    • 检查状态:systemctl status postgresql
    • 启动服务:sudo systemctl start postgresql
  • Windows:
    • 打开「服务」管理器,找到PostgreSQL服务,确认状态为「正在运行」,未运行则右键启动

2. 配置PostgreSQL允许TCP/IP连接

PostgreSQL默认可能未开启TCP监听,需修改配置文件:

  1. 定位配置文件目录:
    • macOS:/usr/local/var/postgres/
    • Linux:/etc/postgresql/<你的PostgreSQL版本>/main/
  2. 编辑postgresql.conf:
    • 找到listen_addresses项,去掉注释符号#,设置为:
      listen_addresses = '*'
      
      (仅允许本地连接可设为listen_addresses = 'localhost,127.0.0.1')
  3. 编辑pg_hba.conf:
    • 添加或保留以下配置,允许本地TCP连接:
      host    all             all             127.0.0.1/32            scram-sha-256
      
      (旧版本PostgreSQL可将scram-sha-256替换为md5)
  4. 重启PostgreSQL服务使配置生效

3. 核对database.yml配置细节

  • 尝试将host改为127.0.0.1,避免localhost解析异常:
    default: &default
      adapter: postgresql
      encoding: unicode
      username: postgres
      password: 123
      host: 127.0.0.1
      port: 5432
    
  • 确认port: 5432与PostgreSQL实际监听端口一致,若修改过端口需同步更新
  • 开发环境可临时移除password字段,同时在pg_hba.conf将本地连接认证改为trust(仅限开发环境,生产环境禁用):
    host    all             all             127.0.0.1/32            trust
    

4. 测试直接连接PostgreSQL

用psql命令排查数据库服务本身的连接问题:

psql -U postgres -h 127.0.0.1 -p 5432

若能成功进入PostgreSQL命令行,说明服务正常,再执行Rails数据库创建命令:

rails db:create

内容的提问来源于stack exchange,提问作者macindex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:14:53