乘客忽略 RAILS_ENV

Passenger Ignoring RAILS_ENV

背景

我有一个 env 文件,其中包含我的 Rails 应用程序所依赖的各种变量,包括 RAILS_ENV,它已在此文件中初始化为开发。我还有 database.yml 文件为我的环境定义数据库连接(如下)。当我 运行 rails 控制台时,一切看起来都应该如此。检查 Rails.configuration.database_configuration[Rails.env] returns 以下内容:

{"adapter"=>"postgresql",
"encoding"=>"utf8",
"database"=>"dev",
"username"=>"rails",
"password"=>"***",
"host"=>"localhost",
"pool"=>5,
"timeout"=>5000}

但是,当我尝试访问应用程序时,收到 502 并记录了以下错误:

Exception ActiveRecord::NoDatabaseError in Rack application object (FATAL: database "prod" does not exist.

显然,错误消息是准确的,但并不代表我预期会发生什么。

我假设这是一个 Passenger/Apache 问题,因为 运行ning rails 控制台一切正常。

注意:我在其他帖子中看到过这种情况,所以没有 - 没有 DATABASE_URL 环境变量漂浮在覆盖 database.yml 的东西周围。

我试过的

  1. .bashrcPassenger is supposed to source the bashrc for the user apache is running as,这又被设置为获取相关的 env 文件。
  2. /etc/sysconfig/httpd:我已经尝试直接从 Apache 配置中手动获取文件,并在脚本 运行s 将正确的值放入 env 时通过将 env 转储到文件进行验证,然而,这也不会改变损坏的行为。

database.yml

development:
  adapter: postgresql
  encoding: utf8
  database: dev
  username: rails
  password: <%= ENV['RAILS_DB_PWD'] %>
  host: <%= ENV['RAILS_DB_HOST'] %>
  pool: 5
  timeout: 5000

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: postgresql
  encoding: utf8
  database: test
  username: rails
  password: <%= ENV['RAILS_DB_PWD'] %>
  host: <%= ENV['RAILS_DB_HOST'] %>
  pool: 5
  timeout: 5000

production:
  adapter: postgresql
  encoding: utf8
  database: prod
  username: rails
  password: <%= ENV['RAILS_DB_PWD'] %>
  host: <%= ENV['RAILS_DB_HOST'] %>
  port: 5432
  pool: 5
  timeout: 5000

一个更好的方法是简单地使用 DATABASE_URL env var.

If you have both config/database.yml and ENV['DATABASE_URL'] set then Rails will merge the configuration together.
Rails Guides: Configuring a Database

common: &common
  adapter: postgresql
  encoding: utf8
  template: template0 # Required for UTF8 encoding
  pool: 5
  timeout: 5000

development:
  <<: *common
  database: dev

test:
  <<: *common
  database: test

production:
  <<: *common
  database: prod

我通常建议您避免在 database.yml 中指定数据库用户名和密码。使用环境变量卢克!当你走到一半时,最好坚持约定优于配置方法,而不是引入单独的变量。

A litmus test for whether an app has all config correctly factored out of the code is whether the codebase could be made open source at any moment, without compromising any credentials. https://12factor.net/config