skip to content

Deploying & Running

Taking a Rails app to production: the generated Dockerfile and Thruster, production.rb and the /up check, Puma threads and workers, and boot and memory tuning. Interviewers probe the defaults.

part ofRuby on Railsread it →
on this pageshow

explore

questions

19

In the Dockerfile that Rails 8.1's `rails new` generates, what do the base, build and final stages each do, and what ends up in the image you run?

level: juniorimportance: must knowfreq 58%

answer

  1. three stages: base, build, final
  2. compilers and -dev headers only in build
  3. bundle install, bootsnap, assets:precompile
  4. COPY --from=build gems and /rails
  5. USER 1000:1000, then ENTRYPOINT and CMD

basics

~20 s

The base stage sets RAILS_ENV=production, the Bundler variables and runtime packages; the build stage adds compilers, installs gems and precompiles assets; the final stage restarts from base, copies only gems and app, and runs as UID 1000.

solid answer

~40 s

The generated Dockerfile has three stages. `base` starts from `ruby:$RUBY_VERSION-slim`, sets `WORKDIR /rails`, installs runtime packages (curl, jemalloc, libvips, the database client) and sets `RAILS_ENV="production"`, `BUNDLE_DEPLOYMENT="1"`, `BUNDLE_PATH="/usr/local/bundle"` and `BUNDLE_WITHOUT="development"`. `build` inherits that, installs `build-essential`, `git`, `pkg-config`, `libyaml-dev` and the database `-dev` package, runs `bundle install`, `bootsnap precompile` and `SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile`. The final stage starts again `FROM base`, creates a `rails` user with UID/GID 1000, switches to `USER 1000:1000` and copies `/usr/local/bundle` and `/rails` from `build` with `--chown=rails:rails`. So the image you run has the gems, the app and its compiled assets, but no compilers and no root process; `ENTRYPOINT` runs `bin/docker-entrypoint` and `CMD` runs `./bin/thrust ./bin/rails server`.

code

dockerfile · 22 lines
dockerfile
FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base
WORKDIR /rails
ENV RAILS_ENV="production" \
    BUNDLE_DEPLOYMENT="1" \
    BUNDLE_PATH="/usr/local/bundle" \
    BUNDLE_WITHOUT="development"

FROM base AS build
COPY Gemfile Gemfile.lock ./
RUN bundle install
COPY . .
RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile

FROM base
RUN groupadd --system --gid 1000 rails && \
    useradd rails --uid 1000 --gid 1000 --create-home --shell /bin/bash
USER 1000:1000
COPY --chown=rails:rails --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}"
COPY --chown=rails:rails --from=build /rails /rails
ENTRYPOINT ["/rails/bin/docker-entrypoint"]
EXPOSE 80
CMD ["./bin/thrust", "./bin/rails", "server"]

go deeper

for a junior

Name the three stages and say what each contributes: production settings, a throwaway build with compilers, and a final image that runs as an unprivileged user.

for a middle

Explain the BUNDLE_* variables, why assets precompile with SECRET_KEY_BASE_DUMMY, and why COPY --from=build copies only the gem directory and /rails.

for a senior

Show you can extend the file safely: runtime versus -dev packages, frozen lockfile failures in CI, and keeping keys and caches out of every layer.

for a principal

Weigh keeping the generated Dockerfile close to upstream for easy upgrades against customising it, and decide who owns base-image and Ruby version bumps.

## Why the generated Dockerfile is split in three Since Rails 7.1, `rails new` writes a production `Dockerfile` (plus `.dockerignore` and `bin/docker-entrypoint`) unless you pass `--skip-docker`. Its header says it is "designed for production, not development" and is meant to be built and run with Kamal or by hand with `docker build` and `docker run`. The file uses three stages so that everything needed to *build* the app (a C compiler, header packages, git) never reaches the image that *runs* it. ## The base stage: what every later stage shares `base` starts from `docker.io/library/ruby:$RUBY_VERSION-slim`, where `RUBY_VERSION` is an `ARG` set to the Ruby that generated the app (keep it in step with `.ruby-version`). It then: - sets `WORKDIR /rails`, so the app lives at `/rails`; - installs **runtime** packages only: `curl` (the generator adds it for Kamal's default health check), `libjemalloc2`, `libvips` unless Active Storage is skipped, and the database client (`postgresql-client`, `default-mysql-client` or `sqlite3`); - sets the environment that every stage inherits: `RAILS_ENV="production"`, `BUNDLE_DEPLOYMENT="1"`, `BUNDLE_PATH="/usr/local/bundle"`, `BUNDLE_WITHOUT="development"` and an `LD_PRELOAD` line that loads jemalloc. Two Bundler details interviewers probe: 1. `BUNDLE_DEPLOYMENT=1` freezes the lockfile: if `Gemfile` and `Gemfile.lock` disagree, `bundle install` fails with a frozen-mode error instead of rewriting the lock. The explicit `BUNDLE_PATH` wins over the `vendor/bundle` path deployment mode would otherwise pick. 2. `BUNDLE_WITHOUT="development"` drops only gems whose every group is excluded. In the generated Gemfile that is `web-console`; `debug`, `brakeman`, `rubocop-rails-omakase` and `bundler-audit` (in `group :development, :test`) and `capybara` / `selenium-webdriver` (in `group :test`) are still installed. They are not loaded at runtime, because `config/application.rb` calls `Bundler.require(*Rails.groups)`, which requires the default group and the current environment's group (plus any named in `RAILS_GROUPS`). ## The build stage: compile once, throw it away `build` is `FROM base AS build`, so it already has production settings. It adds `build-essential`, `git`, `pkg-config`, `libyaml-dev` and the database's `-dev` package (`libpq-dev` or `default-libmysqlclient-dev`; nothing for SQLite), plus Node or Bun only when the app was generated with a JavaScript bundler. Then, in order: 1. copies `vendor/*`, `Gemfile` and `Gemfile.lock`, runs `bundle install` and deletes the gem caches and git checkouts' `.git` directories; 2. runs `bootsnap precompile -j 1 --gemfile` for the gems; 3. copies the rest of the app (`COPY . .`) and runs `bootsnap precompile -j 1 app/ lib/`; 4. unless the app is API-only or skips the asset pipeline, runs `SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile`, so assets compile without the master key. ## The final stage: only what runs The last `FROM base` has no name and becomes the image. It creates a `rails` system group and user with GID and UID 1000, switches to `USER 1000:1000`, and copies two directories from `build` with `--chown=rails:rails`: the installed gems at `/usr/local/bundle` and the app at `/rails` (now including `public/assets` and the bootsnap cache). It ends with `ENTRYPOINT ["/rails/bin/docker-entrypoint"]` and, with Thruster, `EXPOSE 80` plus `CMD ["./bin/thrust", "./bin/rails", "server"]`. | Stage | Adds | Survives into the image? | |---|---|---| | `base` | Ruby, runtime packages, `RAILS_ENV` and `BUNDLE_*` variables | Yes, the final stage starts from it | | `build` | Compilers, `-dev` headers, gem install, bootsnap cache, compiled assets | Only `/usr/local/bundle` and `/rails` are copied out | | final | `rails` user, ownership, `ENTRYPOINT`, `CMD` | Yes, this is the image | ## Variations the generator applies - `--skip-thruster` swaps the last lines for `EXPOSE 3000` and `CMD ["./bin/rails", "server"]`. - `--api` or `--skip-asset-pipeline` drops the `assets:precompile` line. - `--skip-bootsnap` drops both `bootsnap precompile` steps. - `--skip-active-record` removes the database packages and the `db:prepare` block from the entrypoint. ## Edits that break it Interviewers often hand over a modified copy and ask what goes wrong: - **A runtime library added only to `build`.** The gem's extension compiles, but the final stage starts from `base`, so the shared library is missing and `require` fails at boot. - **`COPY` without `--chown` after `USER 1000:1000`.** `COPY` creates files owned by root unless told otherwise, so the app user cannot write `tmp/`, `log/` or `storage/`. - **Assuming test gems are already excluded.** `BUNDLE_WITHOUT="development"` still installs the `:test` group; list `"development:test"` if the image should not carry `capybara` and `selenium-webdriver`. - **Bumping `.ruby-version` alone.** The `ARG RUBY_VERSION` default must change with it, or the image builds on the old Ruby. Read this way, every line has a reason: build tools and caches stay in `build`, secrets stay out of the build, and the running process is an unprivileged user that owns only the files it needs.

  • Why does the final stage start from `base` rather than from `build`?
    Starting from `base` gives the final image Ruby, the runtime packages and the production environment variables without the compilers, header packages and gem caches the `build` stage installed. Only the two directories copied with `COPY --from=build`, the gems and `/rails`, carry over, so the image stays smaller and has less installed software to patch.
  • The bookstore app adds a gem with a C extension that links against a system library. What do you change in the generated Dockerfile?
    Add the library's `-dev` package to the `build` stage's `apt-get install` so the extension compiles, and add the runtime library package to the `base` stage so the compiled extension can load in the final image. Installing only the `-dev` package in `build` makes the image build but fail when the gem is required.

  • The final image still contains build-essential and the compiler toolchain
  • BUNDLE_WITHOUT=development skips every gem in the development and test groups
  • The container runs as root because the Dockerfile never switches user
  • The final stage runs bundle install again against the Gemfile
  • config/master.key is copied in so production can decrypt credentials

Assumes the Rails 8.1 app generator; the Dockerfile arrived in 7.1, jemalloc in 7.2 and Thruster as the default CMD in 8.0.

open as a page

In a Rails 8.1 app, what does the generated `/up` route do, and what does a 200 from `Rails::HealthController` actually prove to a load balancer?

level: juniorimportance: must knowfreq 52%

basics

~20 s

/up routes to Rails::HealthController#show, which answers 200 with a green page, or JSON status: "up", once the app has booted and can serve a request. It does not check the database, cache or job queue.

open as a page

In a new Rails 8.1 app, what does the generated config/puma.rb set up, and what does it leave to Puma's own defaults?

level: juniorimportance: must knowfreq 55%

basics

~20 s

Rails 8.1's config/puma.rb sets threads per process from RAILS_MAX_THREADS (default 3), the port from PORT (default 3000), and loads plugin :tmp_restart. It has no workers line, so Puma reads WEB_CONCURRENCY itself and otherwise runs one process.

open as a page

What does Thruster add in front of Puma in a Rails 8.1 container, and how do the Dockerfile's `EXPOSE 80` and Puma's port 3000 fit together?

level: middleimportance: must knowfreq 45%

basics

~20 s

Thruster is a small Go proxy the Dockerfile runs as ./bin/thrust ./bin/rails server: it starts Puma on PORT 3000, listens on port 80 itself, and adds gzip, caching of public responses, X-Sendfile, HTTP/2 and optional Let's Encrypt TLS.

open as a page

A ticket-resale Rails 8.1 app on a 4-core server, running the generated config/puma.rb, keeps one core busy; why, and what do you change?

level: middleimportance: must knowfreq 60%

basics

~20 s

With WEB_CONCURRENCY unset, Puma runs a single process, and its 3 threads take turns running Ruby under the GVL, so roughly one core works. Setting WEB_CONCURRENCY=4 (or auto) forks four workers, each with its own threads.

open as a page

For a Rails 8.1 app on Puma, how do you choose processes per CPU core and threads per process when optimizing for throughput versus latency?

level: seniorimportance: must knowfreq 50%

basics

~20 s

Processes give parallelism and threads only overlap I/O. For throughput, run one process per core and raise threads until latency suffers; for latency, keep threads low, even one per process with about 1.3 to 1.5 processes per core.

open as a page

In a Rails 8.1 app's generated `bin/docker-entrypoint`, when does `db:prepare` run, and why does it not run for `bin/rails console` or a `bin/jobs` container?

level: middleimportance: should knowfreq 40%

basics

~10 s

The entrypoint runs ./bin/rails db:prepare only when the command's last two arguments are exactly ./bin/rails and server, as in the default thrust CMD; a console, bin/jobs or a server with extra flags skips it.

open as a page

Why does the Rails 8.1 generated Dockerfile run `SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile`, and what would go wrong without that variable?

level: middleimportance: should knowfreq 38%

basics

~10 s

Precompiling boots the production app, and production looks up secret_key_base in SECRET_KEY_BASE or encrypted credentials. The build has no master key, so SECRET_KEY_BASE_DUMMY makes Rails generate a throwaway secret in tmp/local_secret.txt instead.

open as a page

In a Rails 8.1 app, what do Bootsnap's load-path and compile caches save at boot, and why does the generated Dockerfile run bootsnap precompile?

level: middleimportance: should knowfreq 40%

basics

~20 s

Bootsnap caches where each required file lives on $LOAD_PATH and the compiled bytecode of Ruby files, plus parsed YAML. The Dockerfile runs bootsnap precompile so those caches ship inside the image and containers skip compiling at boot.

open as a page

In Rails 8.1, what does config.yjit default to in each environment, and what changes when you set it to false or a Hash?

level: middleimportance: should knowfreq 35%

basics

~10 s

Under load_defaults 8.1, config.yjit is !Rails.env.local?: off in development and test, on in production and other environments. false makes Rails skip enabling YJIT; a Hash enables it with those options, such as mem_size.

open as a page

In a Rails 8.1 app's production.rb, what do `config.public_file_server.headers` and `config.asset_host` each control once a CDN fronts the pet-insurance quote site?

level: middleimportance: should knowfreq 34%

basics

~20 s

public_file_server.headers sets the response headers on every file Rails serves from public/, generated as a one-year public Cache-Control. asset_host makes asset helpers emit URLs on another host, such as a CDN that pulls those files from the app.

open as a page

How does Rails 8.1 decide `Rails.env` from `RAILS_ENV` and `RACK_ENV`, and what do `Rails.env.production?` and `Rails.env.local?` return on a staging deploy?

level: middleimportance: should knowfreq 36%

basics

~10 s

Rails.env takes RAILS_ENV, falls back to RACK_ENV, then to "development", ignoring empty values. With RAILS_ENV=staging, Rails.env.staging? is true while production? and local? are false; local? is true only for development and test.

open as a page

In a Rails app on Puma, how should Active Record's connection pool relate to threads and workers, and what breaks when it is too small?

level: middleimportance: should knowfreq 50%

basics

~20 s

Each Puma process has its own Active Record pool, which must hold at least as many connections as that process has threads. Smaller, and threads wait 5 seconds, then raise ActiveRecord::ConnectionTimeoutError; the server's total is workers times pool.

open as a page

In Rails 8.1's generated deploy files for a SQLite bookstore on one rented server, why does `.dockerignore` exclude `storage/` while `config/deploy.yml` mounts a volume at `/rails/storage`?

level: seniorimportance: should knowfreq 28%

basics

~20 s

storage/ holds state: SQLite files, local Active Storage uploads and Thruster's certificates. .dockerignore keeps the developer's copies and key files out of the image, and deploy.yml's volume keeps production's copies alive when each deploy replaces the container.

open as a page

Puma workers in a large legacy Rails marketplace grow from 400 MB to 1.2 GB daily on glibc malloc; why might the allocator be to blame, and what do jemalloc and MALLOC_ARENA_MAX=2 change?

level: seniorimportance: should knowfreq 40%

basics

~20 s

With several Puma threads per worker, glibc malloc spreads allocations over many arenas and fragments, so freed memory is not returned and RSS creeps. jemalloc, preloaded via LD_PRELOAD as Rails' Dockerfile does, fragments far less; MALLOC_ARENA_MAX=2 limits arenas but can slow Ruby.

open as a page

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%

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.

open as a page

In Rails 8.1, what changes when the pet-insurance quote app's staging runs RAILS_ENV=staging with its own environment file instead of RAILS_ENV=production with staging ENV values?

level: seniorimportance: should knowfreq 30%

basics

~20 s

RAILS_ENV=staging needs its own staging.rb, a database.yml entry and staging credentials, and skips production?-only code and :production gems. RAILS_ENV=production with staging ENV values runs the exact production code path and differs only in configuration values.

open as a page

In Puma cluster mode for a Rails app, what does preload_app! change, and why can a preloaded cluster not do a phased restart?

level: seniorimportance: should knowfreq 38%

basics

~20 s

preload_app! boots the Rails app once in Puma's master and forks workers from it, sharing memory and speeding worker start. A phased restart re-forks workers from that master, which still holds old code, so Puma falls back to a hot restart.

open as a page

For a large legacy Rails marketplace's app-server fleet, how would you set a boot-time and memory budget, and which levers would you trade against each other?

level: principalimportance: nice to knowfreq 18%

basics

~20 s

Set two budgets: time from container start to serving, and resident memory per warmed worker times workers per host. Bootsnap and slimmer load paths cut boot; preloading, jemalloc, YJIT limits and host size move memory; trade them against latency.

open as a page