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

Rails执行db:create报错:无法解析主机名'db'到地址

Rails本地创建PostgreSQL数据库报错:PG::ConnectionBad 解决方法

问题场景

本地重新运行旧Rails项目,前端正常,但执行创建数据库命令时出错:

$ rails db:create

报错信息:

rails aborted!
PG::ConnectionBad: could not translate host name "db" to address: nodename nor servname provided, or not known

项目的database.yml配置如下:

default: &default
  adapter: postgresql
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  host: <%= ENV.fetch("DB_HOST") { "localhost" } %>
  username: <%= ENV.fetch("DB_USERNAME") { "postgres" } %>
  password: <%= ENV.fetch("DB_PASSWORD") { nil } %>
  timeout: 5000

development:
  <<: *default
  database: sample_development

test:
  <<: *default
  database: sample_test

production:
  <<: *default
  database: sample_production

问题原因

报错里的主机名是db,但你的database.yml默认优先读取环境变量DB_HOST,取不到才用localhost。这说明你本地环境里设置了DB_HOST=db——这个主机名一般是Docker容器中的服务名,本地系统没有对应的DNS解析,所以无法连接PostgreSQL。

解决方法

1. 临时修复(单次生效)

在终端执行以下命令,临时清空DB_HOST环境变量后再创建数据库:

unset DB_HOST && rails db:create

2. 永久修改环境变量

如果你的环境变量保存在.env文件或者shell配置文件(如~/.bashrc、~/.zshrc)中:

  • 找到DB_HOST=db这一行,修改为DB_HOST=localhost
  • 保存后重启终端,或者执行source ~/.zshrc(对应你的shell配置文件)使变更生效

3. 直接修改database.yml(不推荐,优先用环境变量管理)

将默认配置里的host行改为固定的localhost:

default: &default
  # ...其他配置
  host: localhost
  # ...其他配置

额外检查点

  • 确保本地PostgreSQL服务已启动:
    • Mac(brew安装):brew services start postgresql
    • Linux:sudo systemctl start postgresql
  • 测试本地PostgreSQL连接是否正常:执行psql -U postgres,能正常进入命令行说明服务和用户名配置没问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 10:50:24