0
0
Ruby on Railsframework~5 mins

Puma server configuration in Ruby on Rails

Choose your learning style9 modes available
Introduction

Puma is a web server that helps your Rails app handle many users at the same time. Configuring Puma lets you control how your app runs smoothly and fast.

When you want your Rails app to handle multiple users without slowing down.
When deploying your Rails app to production and need to optimize performance.
When you want to customize how many threads or workers Puma uses.
When you want to set the port or environment Puma runs in.
When you want to log Puma activity or manage server timeouts.
Syntax
Ruby on Rails
# config/puma.rb

threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i
threads threads_count, threads_count

port        ENV.fetch("PORT") { 3000 }

environment ENV.fetch("RAILS_ENV") { "development" }

workers ENV.fetch("WEB_CONCURRENCY") { 2 }

preload_app!

on_worker_boot do
  ActiveRecord::Base.establish_connection if defined?(ActiveRecord::Base)
end

The threads line sets minimum and maximum threads Puma uses.

The workers line sets how many separate processes Puma runs for better performance.

Examples
This sets Puma to use between 1 and 5 threads, listen on port 3000, and run in development mode.
Ruby on Rails
threads 1, 5
port 3000
environment 'development'
This configures Puma to run 3 worker processes and preload the app for faster worker startup.
Ruby on Rails
workers 3
preload_app!
on_worker_boot do
  ActiveRecord::Base.establish_connection
end
This uses environment variables to set the port and environment, with defaults if not set.
Ruby on Rails
port ENV.fetch("PORT") { 8080 }
environment ENV.fetch("RAILS_ENV") { "production" }
Sample Program

This is a complete Puma configuration file for a Rails app. It sets threads, port, environment, and workers using environment variables with defaults. It preloads the app and reconnects the database on worker boot.

Ruby on Rails
# config/puma.rb

threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i
threads threads_count, threads_count

port        ENV.fetch("PORT") { 3000 }

environment ENV.fetch("RAILS_ENV") { "development" }

workers ENV.fetch("WEB_CONCURRENCY") { 2 }

preload_app!

on_worker_boot do
  ActiveRecord::Base.establish_connection if defined?(ActiveRecord::Base)
end
OutputSuccess
Important Notes

Use environment variables to easily change settings without editing the file.

Preloading the app helps workers start faster but needs proper database reconnect.

Adjust threads and workers based on your server's CPU and memory for best performance.

Summary

Puma configuration controls how your Rails app handles requests.

Set threads, workers, port, and environment to match your needs.

Use preload_app! and on_worker_boot for better worker management.