`initialize':postgres方案不接受注册表部分:postgres:@(或坏主机名?)(URI :: InvalidURIError)与Docker

时间:2015-12-08 07:54:55

标签: ruby-on-rails ruby postgresql ruby-on-rails-4 docker

我使用附加了Postgres DB Docker容器的Rails。当我运行rails c时,我似乎遇到了错误:

/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/uri/generic.rb:204:in `initialize': the scheme postgres does not accept registry part: postgres:@ (or bad hostname?) (URI::InvalidURIError)

这有什么原因吗?

我的database.yml是:

production:
  <<: *default
  url: <%= ENV['DATABASE_URL'] %>

$DATABASE_URL已定义

有趣的是,它在昨天工作了几天,今天又停止了工作。

以下是Rails 4.2.1生成的内容!

# As with config/secrets.yml, you never want to store sensitive information,
# like your database password, in your source code. If your source code is
# ever seen by anyone, they now have access to your database.
#
# Instead, provide the password as a unix environment variable when you boot
# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database
# for a full rundown on how to provide these environment variables in a
# production deployment.
#
# On Heroku and other platform providers, you may have a full connection URL
# available as an environment variable. For example:
#
#   DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase"
#
# You can use this database configuration with:
#
#   production:
#     url: <%= ENV['DATABASE_URL'] %>

为什么他们会推荐保留的env变量??

  

更新:实际上这仍然没有修复。在运行database.yml时,rails runner文件似乎没有从url:文件中获取环境变量,该文件由cron任务运行以调用Sidekiq工作者作业(使用Whenever)。我不得不将docker静态值改为现在让它工作但是考虑到rails runner ip每次从图像运行时我都希望{{1}}正确地选择环境变量。这可能与https://github.com/rails/rails/issues/19256#issuecomment-102980786有关,但解决方案也无效。

3 个答案:

答案 0 :(得分:10)

重命名您的环境变量!

DATABASE_URL由Rails保留,由ActiveRecord本身解释。我遇到了同样的问题。

相反,请使用以下内容:

    host:     <%= ENV['DB_HOST'] %>
    password: <%= ENV['DB_PWD'] %>

答案 1 :(得分:4)

"Configuring Rails Applications" guide开始,DATABASE_URL似乎用于配置数据库访问。配置数据库访问的另一种方法是存在文件config/database.yml。尝试使用这两种方法配置数据库访问会导致您遇到的问题。

如果您的密码包含不安全的字符

用于DATABASE_URL的连接字符串不能包含特殊字符([a-zA-Z0-9_~-\.]以外的任何字符,例如@是常见问题)。解决方案是url-encode。

如果你正在使用dokku

如果您使用的是pghero

答案 2 :(得分:2)

接受的答案是错误的。尽管doing so explicitly is probably redundant,但在DATABASE_URL中使用database.yml并没有错。问题出在URL的值上。

ActiveRecord使用URI::RFC2396_Parser解析数据库URL。上面的错误消息表明它无法解析URL,可能是因为缺少主机名,请参见。

URI::RFC2396_Parser.new.parse('postgres://postgres:@/mydb')
# Traceback (most recent call last):
#       1: from (irb):30
# URI::InvalidURIError (the scheme postgres does not accept registry part: postgres:@ (or bad hostname?))

其他无效的主机名,例如带下划线的主机名(在docker-compose设置中常见)将导致类似的错误:

URI::RFC2396_Parser.new.parse('postgres://postgres:postgres@my_postgres/mydb')
# Traceback (most recent call last):
#        1: from (irb):34
# URI::InvalidURIError (the scheme postgres does not accept registry part: postgres:postgres@my_postgres (or bad hostname?))

尤其令人困惑的是,URI.parse()使用URI::RFC3986_Parser,它更宽容,并且会接受这些“不良” URL中的任何一个。