Learning objectives
After reading this article you will be able to:
- Configure RAILS_ENV, the secret key and the database through DATABASE_URL
- Tune Puma workers and threads to the memory you have
- Keep assets, migrations, Active Storage and Sidekiq out of the web process
On this page
- Which environment variables does Rails need in production?
- How do you install gems for production?
- How do you configure Puma?
- How do you prepare assets and migrations on each deploy?
- Where should Active Storage files live?
- How do you run jobs with Sidekiq?
- Which errors show up after the deploy?
- How to do this on Square Cloud
- FAQs
In development, bin/rails server hides almost everything production needs: it runs in the development environment, generates a throwaway secret, compiles assets on demand and shows detailed errors in the browser. Once you deploy, Rails expects a real secret key, precompiled assets, a database configured through a variable and an app server tuned to the memory you have.
The path below works on a VPS, in a container or on a hosting platform: variables, gems, Puma, assets and migrations, uploaded files and jobs. For the big picture of shipping a backend, see how to host an API.
Which environment variables does Rails need in production?#
RAILS_ENV=production
RAILS_MASTER_KEY=contents_of_config_master_key
DATABASE_URL=postgres://user:password@db-host:5432/myapp
RAILS_LOG_LEVEL=info
WEB_CONCURRENCY=2
RAILS_MAX_THREADS=3RAILS_ENV=production: loadsconfig/environments/production.rb, with caching on, error pages without details for visitors and, in apps generated by recent releases, logs toSTDOUT, where your host can show them.- The secret key: Rails looks for
secret_key_basefirst in theSECRET_KEY_BASEvariable and then in the encrypted credentials (config/credentials.yml.enc). To decrypt the credentials, it usesconfig/master.keyor theRAILS_MASTER_KEYvariable. The credentials file can go into Git; the master key, never. To generate a freshSECRET_KEY_BASE, runbin/rails secret. DATABASE_URL: Rails merges this URL withconfig/database.yml. Values that only exist in the YAML, such as the connection pool size, still apply, and the URL wins on conflicts. That way, no password lives in the repository.
For the concept behind this, see what environment variables are.
How do you install gems for production?#
bundle config set --local without 'development test'
bundle installThe without setting skips the development and test groups of your Gemfile and is saved in .bundle/config. Every Bundler setting also works as an environment variable with the BUNDLE_ prefix: BUNDLE_WITHOUT=development:test has the same effect, which helps when you don't control the install command. For a reproducible deploy, BUNDLE_DEPLOYMENT=1 freezes the versions in Gemfile.lock and installs into vendor/bundle. Always ship Gemfile.lock: without it, each install may resolve different versions.
How do you configure Puma?#
Puma is the app server Rails already generates a config for in config/puma.rb. The part that matters:
threads_count = ENV.fetch("RAILS_MAX_THREADS", 3)
threads threads_count, threads_count
port ENV.fetch("PORT", 3000)
plugin :tmp_restart- Threads: each process serves up to
RAILS_MAX_THREADSrequests at once. The generated file's comment explains the default of 3: more threads raise throughput but, because of CRuby's GVL, can hurt response time. - Workers: Puma reads
WEB_CONCURRENCYon its own. Without the variable, it runs a single process; with 2 or more, it forks child processes that use several CPU cores. Each worker loads a copy of the app, so memory grows with every worker you add. - Database pool:
max_connectionsindatabase.yml(calledpoolin older apps) must be at least the number of threads per process. The total opened is workers times threads, and it has to fit within the database's limit; see the too many connections error. - Port and interface: Puma's
portlistens on every interface, not just localhost. If you start withbin/rails serverinstead, pass-b 0.0.0.0 -p $PORT.
The production command is bundle exec puma -C config/puma.rb.
How do you prepare assets and migrations on each deploy?#
SECRET_KEY_BASE_DUMMY=1 bin/rails assets:precompile
bin/rails db:migrate
bundle exec puma -C config/puma.rbassets:precompile writes fingerprinted files to public/assets. It boots the app, which in production requires secret_key_base; with SECRET_KEY_BASE_DUMMY=1, Rails uses a temporary secret, so you can compile in CI without exposing the real key. If the app uses jsbundling or cssbundling, precompile also runs the JavaScript and CSS build, and then Node.js has to be present.
db:migrate applies pending migrations. Run it before the new code takes traffic and prefer changes the previous release can live with, because for a moment both may run side by side. Details in migrations on deploy.
If a proxy terminates HTTPS in front of Puma, check that production.rb has these active (the generator may leave them commented out): config.assume_ssl = true, so Rails treats every request as HTTPS, and config.force_ssl = true, which redirects to HTTPS, sends HSTS and marks cookies as secure. If you enable config.hosts against Host header attacks, include your public domain, or Rails rejects the requests.
Where should Active Storage files live?#
The generated production.rb points Active Storage at :local, the server's disk. That works on a single-instance VPS, but files vanish when the disk is recreated and a second instance can't see them; the problem is covered in why uploaded files disappear after a deploy. The fix is S3-compatible object storage. Add gem "aws-sdk-s3", require: false to the Gemfile and configure config/storage.yml:
s3:
service: S3
endpoint: <%= ENV["S3_ENDPOINT"] %>
access_key_id: <%= ENV["S3_ACCESS_KEY_ID"] %>
secret_access_key: <%= ENV["S3_SECRET_ACCESS_KEY"] %>
region: <%= ENV.fetch("S3_REGION", "us-east-1") %>
bucket: <%= ENV["S3_BUCKET"] %>
force_path_style: trueIn production.rb, switch to config.active_storage.service = :s3. The endpoint points at the S3-compatible provider, and force_path_style, an option of the AWS SDK's S3 client, puts the bucket name in the URL path instead of the subdomain; keep it only if your provider asks for it. If the app doesn't have the tables yet, bin/rails active_storage:install generates the migration.
How do you run jobs with Sidekiq?#
Background jobs don't run in the web process: a separate worker reads the queue and runs them (the queue model is covered in how to run background jobs). With Sidekiq, the queue lives in Redis. Add gem "sidekiq", set config.active_job.queue_adapter = :sidekiq and start the worker:
bundle exec sidekiqSidekiq reads the REDIS_URL variable; without it, it tries localhost:6379. The worker needs the same code and the same variables as the web process (RAILS_ENV, the secret key, DATABASE_URL, REDIS_URL), and it must restart on every deploy to load the new code.
In recent releases, Rails generates new apps with Solid Queue, which stores jobs in the database and runs as its own process (bin/jobs) or inside Puma, with SOLID_QUEUE_IN_PUMA=true. To compare the models, see cron vs workers vs queues.
Which errors show up after the deploy?#
The secret key is missing. Neither SECRET_KEY_BASE nor the credentials reached the process:
Missing `secret_key_base` for 'production' environment, set this string with `bin/rails credentials:edit`The master key is missing. Rails tries to read the credentials and can't find RAILS_MASTER_KEY:
Missing encryption key to decrypt file with. Ask your team for your master key and write it to /app/config/master.key or put it in the ENV['RAILS_MASTER_KEY'].The other common errors, with cause and fix:
| Error | Cause | Fix |
|---|---|---|
ActiveSupport::MessageEncryptor::InvalidMessage |
The master key isn't the one that encrypted the credentials file | Check that the value didn't pick up a space or a line break when you pasted it |
| Pages without CSS, or asset not found | assets:precompile didn't run, or public/assets was left out of the upload |
Run precompile in CI or before starting Puma |
ActiveRecord::ConnectionNotEstablished |
DATABASE_URL never reached the process, or it points at localhost |
Set the variable to the database's real host |
ActiveRecord::ConnectionTimeoutError |
Threads wait for a connection because the pool is smaller than RAILS_MAX_THREADS |
Make the pool at least as large as the thread count |
| The process dies from running out of memory | Too many workers for the available RAM | Lower WEB_CONCURRENCY or add memory |
For the last one, see also out-of-memory errors.
How to do this on Square Cloud#
On Square Cloud, the Ruby runtime runs bundle install on the server from your Gemfile, and the start command (START) accepts the bundle exec you already use: Rails, Sinatra and Roda start this way. You can deploy with a ZIP in the dashboard, the CLI, GitHub or the VS Code extension, and squarecloud.app is optional, because the dashboard generates the configuration on deploy. There is no build step: precompile moves to an external CI that ships the finished public/assets, or goes into the START, which runs as a shell command of up to 256 characters. An example START to adapt to your app:
bin/rails assets:precompile && bin/rails db:migrate && bundle exec puma -C config/puma.rbSet RAILS_ENV=production, RAILS_MASTER_KEY (or SECRET_KEY_BASE) and DATABASE_URL in the app's environment variables. They already exist during the install, so a BUNDLE_WITHOUT=development:test reaches Bundler, and the install output shows up in the logs for you to check. A change to the variables applies on the next restart, with no rebuild. The platform sets PORT, which the generated puma.rb already reads, and publishes the app over HTTPS on a *.squareweb.app subdomain: keep config.assume_ssl = true and, if you use config.hosts, include that subdomain.
PostgreSQL, MySQL and Redis hosting starts on Standard, from R$44.99 a month, with TLS required: you copy the connection URL from the dashboard into DATABASE_URL, on PostgreSQL the client also presents the .pem certificate, and Redis uses rediss://. Sidekiq starts from the START with bundle exec sidekiq; one way to set it up is a second, background app (256 MB minimum) with the same code. One app can't read another's variables, so repeat the web process's variables there. The web app uses at least 512 MB of the plan's RAM, and the Puma workers share the memory you give it: if it runs out, the app stops and doesn't come back on its own, so add RAM or lower WEB_CONCURRENCY and start it again.
The app's disk persists across restarts and deploys, so Active Storage's :local works for a single app. With load balancing (from Standard), each app has its own disk, and the files belong in Blob, which has an S3-compatible API (endpoint https://s3-blob.squarecloud.app, region auto, bucket private or public) with keys generated in the dashboard's "S3 access" tab. See the details of Ruby hosting.
API hosting
APIs in always-on containers, with no cold starts
FAQs
Should I use SECRET_KEY_BASE or RAILS_MASTER_KEY?
Both work. RAILS_MASTER_KEY unlocks config/credentials.yml.enc, which holds secret_key_base and your other secrets; SECRET_KEY_BASE sets only the secret key and takes precedence over the credentials. config/master.key never goes into the repository.
How many Puma workers and threads should I use?
Rails generates the app with 3 threads and a single process. Each extra worker is a process with its own copy of the app, so raise WEB_CONCURRENCY only if you have the RAM and CPU, and keep the database connection pool at least as large as the thread count.
Do I have to run assets:precompile on the server?
Not necessarily. You can precompile in CI and ship the finished public/assets folder. With SECRET_KEY_BASE_DUMMY=1, the command runs without the production secrets.
Sidekiq or Solid Queue?
Solid Queue, the default in apps generated by recent Rails releases, stores jobs in your database and needs no Redis. Sidekiq keeps the queue in Redis. Both can run in a process separate from the web server.
More in APIs
See all 36 articles- How to host an APIHosting an API means running its HTTP server around the clock at a public address with HTTPS. Step-by-step with Node.js and Python, testing and common errors.
- How to host a Node.js appTo host a Node.js app, prepare package.json, read the port and secrets from the environment, pick an LTS version and run it with node. Step-by-step guide.
- How much does it cost to host an API?Hosting a small API costs a few to a few dozen dollars a month. See what goes into the bill (compute, database, bandwidth, requests, logs) and how to estimate it.
- CORS error (blocked by CORS policy): cause and fixA CORS error means the API did not allow your page's origin. Learn the causes, how to fix it in Express and FastAPI, and how to test the preflight with curl.