Creating staging and other environments in Rails

Ruby on Rails come with three environments by default – development, testing and production. But sooner or later one has a need for staging environment. And don’t get me wrong, you can (or should?) use the production settings there, but if you run it locally or on the same server as production, chances are you need a different database. And while you are at it, it may be handy to allow logging to console or change any other of Rails settings for that matter. In fact you can create as many other environments as you want and since it’s really easy I encourage you to do so.

To create a new environment you need to create:

As I mentioned first we would need a new file in config/environments/. A short example for staging environment could be config/environments/staging.rb:

# Just use the production settings
require File.expand_path('../production.rb', __FILE__)

Rails.application.configure do
  # Here override any defaults
  config.serve_static_files = true

You might actually want to copy the production.rb environment file, but I am making it short.

To make a new entry in config/database.yml just edit the file and include a new database:

# Production settings for local development and profiling
  database: db_profile

To make a new entry in config/secrets.yml you can use the following Rake command to get a new key base:

$ rake secret
  secret_key_base: 40bf0f5019e785b6b44a29f1680febbcb06db8dd64f835986c6686bebddf304b67f8a9a6dffcc862f2586edc60921d0b736e3e0b1833eea2431767d2a0d1f9cc

# Add this new entry with the generated key base
  secret_key_base: c975f1417b60097ecfc17e308f0d8fc502f1e2534b14ef41527d703923db9e875ad4eeb779a74c732bb6c5747c3b56d84fe7f38554089522a2f557c587766fcc

Also don’t forget on various initializers that might be configured for specific environments. For instance this might be a change you want to do for a rack-mini-profiler initializer inside config/initializers/rack_profiler.rb file:

if Rails.env.development? || Rails.env.staging?
  require 'rack-mini-profiler'

  # Initialization is skipped so trigger it

  # Needed for staging env
  Rack::MiniProfiler.config.pre_authorize_cb = lambda { |env| true }
  Rack::MiniProfiler.config.authorization_mode = :allowall

As you can see some gems for development don’t assume you want to use them elsewhere.

Now you can go ahead and prepend your commands with a new RAILS_ENV values:

$ RAILS_ENV=staging rake db:create

The same way you can then add other environments. The nice thing is that you can use same databases if you want, just different settings (asset management, logging, 3rd party services) or the same config with a different database.


I wrote a complete guide on web application deployment. Ruby with Puma, Python with Gunicorn, NGINX, PostgreSQL, Redis, networking, processes, systemd, backups, and all your usual suspects.

More →