Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 37 ยท Getting Started

Environments and Configuration

Understand Rails environments (development, test, production), database.yml, initializers, encrypted credentials and environment variables, with a runnable YAML and ERB configuration stand-in.

An application behaves differently on your laptop, in the test suite and on a live server. In development you want friendly error pages and reloaded code. In production you want caching, quiet logs and secrets kept safe. Rails handles this with environments and a set of configuration files that each have one job.

In this lesson you will learn the three standard environments, where each kind of setting belongs, how database.yml works (it is YAML with ERB inside), how encrypted credentials replace plain secret files, and why you should never commit secrets. The Rails files are read-only here; the runnable examples reproduce the key mechanisms in plain Ruby with the standard yaml and erb libraries.

The three environments

A Rails app runs in exactly one environment, set by the RAILS_ENV variable.

Environment Used for Typical behaviour
development Your laptop Code reloads on each request, detailed error pages, verbose logs
test The test suite Fresh database, mail not sent, no caching
production The live site Code loaded once, caching on, errors hidden from users

Commands set the environment for you: bin/rails server uses development, bin/rails test uses test, and on a server you set RAILS_ENV=production. In code, ask with Rails.env:

Ruby
# read-only
Rails.env                 # => "development"
Rails.env.production?     # => false
Rails.env.test?           # => false

Each environment has its own file in config/environments/: development.rb, test.rb and production.rb. Settings shared by all live in config/application.rb.

Ruby
# config/environments/production.rb  (read-only, abbreviated)
Rails.application.configure do
  config.enable_reloading = false     # load code once
  config.eager_load = true            # load everything at boot
  config.consider_all_requests_local = false
  config.log_level = :info
  config.force_ssl = true
end

The config folder

Which file for which setting?

application.rb Settings for every environment.
environments/ One file per environment.
database.yml How to reach the database.
1 / 2

config/initializers/*.rb run once at boot, in alphabetical order. They configure libraries, for example inflections, session cookies or a payment gem.

database.yml

config/database.yml tells Active Record how to connect, with one block per environment:

YAML
# config/database.yml  (read-only)
default: &default
  adapter: sqlite3
  max_connections: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: storage/development.sqlite3

test:
  <<: *default
  database: storage/test.sqlite3

production:
  <<: *default
  database: storage/production.sqlite3

Two YAML tricks are used. &default names a block and <<: *default merges it, so shared keys are written once. And <%= ... %> is ERB: Rails runs the file through ERB first, then parses the YAML. That is how environment variables sneak in.

Stand-in: ERB then YAML, with merge keys

This reproduces that two-step loading with the standard libraries. We pick the environment block, just as Rails does.

Ruby Stand-in: load a database.yml with ERB and merge keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The merge key <<: copies the default block into each environment, so a change to adapter happens once.

Credentials and secrets

Passwords, API keys and the secret that signs cookies must not sit in your Git history. Rails keeps them in an encrypted file, config/credentials.yml.enc, which is safe to commit. The key that decrypts it lives in config/master.key (which is not committed) or in the RAILS_MASTER_KEY environment variable on the server.

Terminal
bin/rails credentials:edit          # opens the decrypted file in your editor

Read values from code:

Ruby
# read-only
Rails.application.credentials.stripe[:secret_key]
Rails.application.credentials.dig(:aws, :access_key_id)

Per-environment credentials also exist (config/credentials/production.yml.enc with production.key).

Never commit config/master.key, and never paste a real key into a lesson, chat or issue tracker. If it leaks, generate a new one and rotate every secret stored in the file.

Environment variables

For settings that change per deployment (a database URL, a host name) the common approach is an environment variable read with ENV:

Ruby
# read-only
config.hosts << ENV["APP_HOST"] if ENV["APP_HOST"]
url = ENV.fetch("REDIS_URL", "redis://localhost:6379/1")

ENV.fetch with a default is better than ENV[]: a missing key fails loudly or falls back to a safe default instead of silently being nil.

Stand-in: a layered config object

Rails config is really layers: defaults, then environment-specific values, then environment variables. This stand-in makes that layering visible with a plain Hash.

Ruby Stand-in: defaults, environment values and ENV overrides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

fetch raises KeyError for an environment nobody defined, which is better than quietly using the wrong settings. See error handling in Ruby for the pattern.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which environment variable selects the Rails environment?

    RAILS_ENV (and Rails.env in code) names the environment: development, test or production.
  2. 2. Why does database.yml contain <%= ... %> tags?

    ERB is processed first, so you can read environment variables inside the YAML.
  3. 3. Which file is safe to commit and which must never be committed?

    The encrypted file is useless without the key, so only the key must stay private.
  4. 4. Why prefer ENV.fetch("KEY", default) over ENV["KEY"]?

    fetch with a default is explicit, and without one it raises KeyError for missing values.

Summary

  • Rails runs in development, test or production; Rails.env tells you which.
  • Shared settings go in config/application.rb, per-environment ones in config/environments/, boot-time code in config/initializers/.
  • database.yml is YAML with ERB inside; &default and <<: *default avoid repetition.
  • Secrets live in encrypted credentials; commit the .enc file, never the master key.
  • Use ENV.fetch for per-deployment settings.

Next: Routing Basics