skip to content

Why does adding `config.x.quote_api_url = ENV.fetch("QUOTE_API_URL")` to a Rails 8.1 production.rb break the generated Docker build, and how should environment files read ENV?

level: seniorimportance: should knowfreq 32%

answer

  1. production.rb runs on every production boot
  2. assets:precompile boots during docker build
  3. KeyError: key not found
  4. ENV.fetch with a default or block
  5. ENV values are always strings

basics

~20 s

production.rb runs whenever the app boots in production, including the build stage's assets:precompile, where QUOTE_API_URL is not set, so ENV.fetch raises KeyError and the build fails. Give optional values defaults and read required ones where they are used.

solid answer

~40 s

Environment files are Ruby that runs on **every** production boot: the server, `bin/rails console`, the entrypoint's `db:prepare` and the Dockerfile's `SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile`. The build stage's environment holds the image's own variables, such as `RAILS_ENV` and the `BUNDLE_*` settings, plus the dummy flag, so `ENV.fetch("QUOTE_API_URL")` without a default raises `KeyError` (`key not found: "QUOTE_API_URL"`) and the image never builds. Follow the generated pattern for optional settings, `ENV.fetch("RAILS_LOG_LEVEL", "info")`, and move required runtime values out of boot: fetch them where they are used, such as in the quote client, so a missing value fails loudly when a quote is requested, never during a build. Remember that ENV values are strings: `"false"` is truthy, and `ENV.fetch("X", 3)` returns an Integer only when the variable is unset, so cast explicitly. Secrets belong in credentials.

code

ruby · 11 lines
ruby
# config/environments/production.rb
Rails.application.configure do
  # Breaks docker build: assets:precompile boots production without it
  # config.x.quote_api_url = ENV.fetch("QUOTE_API_URL")

  # Safe at build time: optional values with defaults
  config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info")
  config.x.quote_timeout = Integer(ENV.fetch("QUOTE_TIMEOUT", "5"))
  config.x.quotes_enabled =
    ActiveModel::Type::Boolean.new.cast(ENV.fetch("QUOTES_ENABLED", "true"))
end

go deeper

for a junior

Remember that ENV.fetch without a default raises KeyError when the variable is missing, while ENV[] returns nil.

for a middle

Explain that environment files run on every production boot, including assets:precompile in the build, and use defaults and explicit casts.

for a senior

Diagnose build failures caused by boot-time reads, move required values to their point of use, and keep the image environment-neutral.

for a principal

Set conventions for how configuration enters the app, defaults, required values and secrets, so builds and deploys fail in predictable places.

## Environment files are code that runs at every boot `config/environments/production.rb` is not a static settings file; it is Ruby evaluated each time the application boots in the production environment. In a container built from the generated Dockerfile, that happens in several places: - the web server, `./bin/thrust ./bin/rails server`; - `bin/docker-entrypoint`'s `./bin/rails db:prepare` before the server starts; - `bin/rails console` or `bin/rails runner` on the server; - the build stage's `SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile`, because the base stage sets `RAILS_ENV="production"`. The last one is the trap. During `docker build`, the environment holds the image's own variables (`RAILS_ENV`, `BUNDLE_DEPLOYMENT`, `BUNDLE_PATH`, `BUNDLE_WITHOUT`, `LD_PRELOAD` and what the Ruby base image sets) plus the dummy flag, and nothing your deploy injects at run time. ## How `ENV.fetch` fails Ruby's `ENV.fetch` has three forms: | Call | Variable set | Variable missing | |---|---|---| | `ENV.fetch("QUOTE_API_URL")` | its String value | raises `KeyError`: `key not found: "QUOTE_API_URL"` | | `ENV.fetch("RAILS_LOG_LEVEL", "info")` | its String value | `"info"` | | `ENV.fetch("RAILS_MAX_THREADS") { 5 }` | its String value | the block's result, `5` | So the new line in `production.rb` makes the precompile step raise `KeyError`, the `RUN` fails, and the image is never produced, even though the running server would have had the variable. `ENV["QUOTE_API_URL"]` would not raise, but it would set `nil` and push the failure to the first quote request, with a less obvious error. ## Patterns that survive builds and boots 1. **Optional settings get a default**, as the generated files do: `config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info")`, `port ENV.fetch("PORT", 3000)` in `config/puma.rb`, `max_connections: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>` in `database.yml`. 2. **Required runtime values are read where they are used.** Store nothing at boot, or store a nullable value, and fetch strictly in the code that needs it: ```ruby class QuoteClient def base_url = ENV.fetch("QUOTE_API_URL") end ``` A missing value now raises `KeyError` when a quote is requested, in the server, never during `docker build` or `db:prepare`. 3. **Secrets go to credentials**, read lazily for the same reason; the master key is also absent during the build. 4. **Fail fast at deploy time deliberately**, for example a boot check that the release process runs against the real environment, not an `ENV.fetch` that every rake task trips over. ## Diagnosing the failed build The symptom is a failing `RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile` step with `KeyError: key not found: "QUOTE_API_URL"` in its output. To confirm and fix: 1. Read the backtrace: the first app frame points at the `ENV.fetch` line in `production.rb` or an initializer. 2. Reproduce locally without the variable: `RAILS_ENV=production SECRET_KEY_BASE_DUMMY=1 bin/rails assets:precompile`. 3. Move the read, or give it a default, and rebuild. ## ENV values are strings Every value in `ENV` is a String, which bites configuration code: - `config.x.quotes_enabled = ENV["QUOTES_ENABLED"]` is truthy for `"false"` and `"0"`; compare explicitly (`ENV["QUOTES_ENABLED"] == "true"`) or cast with `ActiveModel::Type::Boolean.new.cast(...)`, which treats `"false"`, `"0"`, `"f"` and `"off"` as false. - `ENV.fetch("QUOTE_TIMEOUT", 5)` returns the Integer `5` when unset and the String `"5"` when set; wrap it in `Integer(...)` so both paths give the same type. - Passing both a default and a block makes Ruby warn that the block supersedes the default. ## Checklist for the quote app - Grep `config/environments/*.rb` and `config/initializers/*.rb` for `ENV.fetch(` calls without a default; each one runs during `assets:precompile`. - Give optional values defaults that are safe in a build. - Move required URLs and keys to the place they are used, or to credentials read lazily. - Cast booleans and integers explicitly. - Keep staging and production differences in these values, so one `production.rb` serves both when staging runs with production settings.

  • Why not just pass QUOTE_API_URL as a build argument so the precompile step has it?
    It couples the image to one environment: the same image could no longer serve staging and production with different URLs, and any build-time value becomes part of the image's history. Images should be environment-neutral, with values injected when the container starts. Removing the boot-time read is the real fix.
  • `config.x.quotes_enabled = ENV["QUOTES_ENABLED"]` keeps quotes on even with `QUOTES_ENABLED=false`. Why?
    ENV values are Strings, and in Ruby every String, including `"false"`, is truthy. Compare explicitly (`ENV["QUOTES_ENABLED"] == "true"`) or cast with `ActiveModel::Type::Boolean.new.cast`, which maps `"false"`, `"0"`, `"f"` and `"off"` to false.

  • production.rb runs only when the web server starts
  • The Docker build sees the same ENV the deploy injects at run time
  • ENV["X"] raises KeyError when X is missing
  • ENV.fetch("X", 3) always returns an Integer
  • QUOTES_ENABLED=false makes ENV["QUOTES_ENABLED"] falsy