Docker撰写:Rails将不尊重DATABASE_URL连接到Postgres

我试图容器化我的Ruby on Rails的5.1.0应用程序,但我有一些麻烦,不从环境中拿DATABASE_URL 。 在docker-compose.yml ,我有以下服务:

 app: build: . command: bundle exec rails s -p 3000 -b '0.0.0.0' volumes: - .:/myapp environment: DATABASE_URL: postgres://postgres:pw@db:5432/myapp_development 

如果我运行docker-compose run app rails c

 $ docker-compose run app rails c Running via Spring preloader in process 25 Loading development environment (Rails 5.1.0) irb(main):001:0> ENV['DATABASE_URL'] => "postgres://postgres:pw@db:5432/myapp_development" 

但是,如果我运行docker-compose run app rake db:create ,我得到一个关于不能连接到localhost的错误:

 $ docker-compose run app rake db:create Database 'myapp_development' already exists could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Couldn't create database for {"adapter"=>"postgresql", "host"=>"localhost", "pool"=>10, "timeout"=>5000, "database"=>"myapp_test"} rake aborted! 

任何想法我在这里做错了吗?

编辑:这是什么database.yml看起来像:

 common: &common adapter: postgresql pool: 10 timeout: 5000 development: <<: *common database: myapp_development test: <<: *common database: myapp_test production: <<: *common database: myapp_production 

问题是在rake任务中,它试图创buildtesting数据库,我假设你的database.yml有一个localhost主机的testing环境。

rake db:create的描述

从当前RAILS_ENV的DATABASE_URL或config / database.yml创build数据库(使用db:create:all在configuration中创build所有数据库)。 没有RAILS_ENV,它默认创build开发和testing数据库

您应该明显地通过env,或者默认情况下可以创build一个testing数据库。

我build议你在database.yml中更改testing数据库database.yml

Connection Preference

我有同样的问题,似乎在Rails 5.1.xconfiguration合并是以某种方式打破

您可以通过在default块中添加url: <%= ENV['DATABASE_URL'] %>来强制使用DATABASE_URL