๐ Ruby on Rails on AlmaLinux: Complete Deployment Guide for Beginners
Welcome to the exciting world of Ruby on Rails deployment! ๐ Today weโll master deploying Rails applications on AlmaLinux, turning your development masterpiece into a production-ready powerhouse. Think of Rails as your magical framework that makes web development a joy, and AlmaLinux as the rock-solid foundation it runs on! ๐๏ธ
Ruby on Rails has powered giants like GitHub, Shopify, and Airbnb. Now itโs your turn to join this amazing community and deploy your Rails applications professionally on AlmaLinux. Letโs transform your local Rails app into a blazing-fast production server! ๐ช
๐ค Why is Ruby on Rails Important?
Ruby on Rails is like having a team of expert developers built into your framework! ๐ฆธ Hereโs why millions of developers love it:
- ๐ Rapid Development - Build applications 10x faster than traditional frameworks
- ๐ Convention Over Configuration - Rails makes smart decisions so you donโt have to
- ๐ง Complete Framework - Everything included: ORM, routing, testing, caching
- ๐ฆ Massive Gem Ecosystem - Thousands of pre-built solutions via RubyGems
- ๐ Developer Happiness - Rails is optimized for programmer joy and productivity
- ๐ฐ High Demand - Rails developers command premium salaries worldwide
- ๐ข Enterprise Ready - Trusted by Fortune 500 companies globally
- ๐ค Amazing Community - Helpful, welcoming, and innovative developer community
๐ฏ What You Need
Before we deploy your Rails masterpiece, make sure you have:
โ
AlmaLinux system (physical or virtual machine)
โ
Root or sudo access for installing packages
โ
At least 2GB RAM (4GB recommended for production)
โ
Basic command line knowledge (weโll guide you through everything!)
โ
A Rails application to deploy (or weโll create one)
โ
Database knowledge (PostgreSQL or MySQL basics)
โ
Text editor like nano or vim
โ
Internet connection for downloading gems and packages
๐ Installing Ruby and Rails Environment
Letโs set up the perfect Ruby on Rails environment! ๐ ๏ธ
# Update your system first
sudo dnf update -y
# This ensures you have the latest packages and security updates
# Install development tools and dependencies
sudo dnf groupinstall -y "Development Tools"
sudo dnf install -y git-core zlib zlib-devel gcc-c++ patch readline readline-devel \
libyaml-devel libffi-devel openssl-devel make bzip2 autoconf automake libtool \
bison curl sqlite-devel
# These packages are required for building Ruby and native extensions
# Install Node.js and Yarn for Rails asset pipeline
sudo dnf install -y nodejs npm
npm install --global yarn
# Rails needs JavaScript runtime for asset compilation
# Install database clients
sudo dnf install -y postgresql-devel mariadb-devel
# Development libraries for PostgreSQL and MySQL/MariaDB
Now letโs install Ruby using rbenv (Ruby version manager):
# Install rbenv and ruby-build
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
# This clones rbenv for managing Ruby versions
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
# Adds rbenv to your shell path
git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
# Adds ruby-build plugin for installing Ruby versions
# Reload your shell configuration
source ~/.bashrc
# Install Ruby (using latest stable version)
rbenv install 3.2.2
# This installs Ruby 3.2.2 (adjust version as needed)
rbenv global 3.2.2
# Sets Ruby 3.2.2 as the default version
# Verify Ruby installation
ruby -v
# Should show: ruby 3.2.2 or your installed version
# Install Rails
gem install rails
# Installs the latest Rails framework
# Verify Rails installation
rails -v
# Should show Rails version (e.g., Rails 7.1.0)
๐ง Creating a Sample Rails Application
Letโs create a Rails application to demonstrate deployment! ๐๏ธ
# Create a new Rails application
rails new myapp --database=postgresql
# Creates a new Rails app with PostgreSQL database
cd myapp
# Enter the application directory
# Add some essential gems to Gemfile
cat >> Gemfile << 'EOF'
# Production server
gem 'puma', '~> 6.0'
# Background jobs
gem 'sidekiq', '~> 7.0'
gem 'redis', '~> 5.0'
# Environment variables
gem 'dotenv-rails', groups: [:development, :test]
# Monitoring
gem 'rack-mini-profiler', group: :development
EOF
# Adds production-ready gems
# Install the gems
bundle install
# Downloads and installs all required gems
# Create a simple controller
rails generate controller Welcome index
# Generates a welcome controller with index action
# Set the root route
echo "Rails.application.routes.draw do
root 'welcome#index'
# Other routes here
end" > config/routes.rb
# Sets the homepage route
Now letโs add some content to our welcome page:
# Create a beautiful welcome page
cat > app/views/welcome/index.html.erb << 'EOF'
<div style="text-align: center; padding: 50px; font-family: Arial, sans-serif;">
<h1>๐ Welcome to Rails on AlmaLinux!</h1>
<p style="font-size: 20px; color: #666;">
Your Ruby on Rails application is running successfully! ๐
</p>
<div style="margin: 30px 0;">
<h2>System Information</h2>
<p>Ruby Version: <%= RUBY_VERSION %></p>
<p>Rails Version: <%= Rails.version %></p>
<p>Environment: <%= Rails.env %></p>
<p>Server Time: <%= Time.current.strftime("%Y-%m-%d %H:%M:%S %Z") %></p>
</div>
<div style="margin-top: 40px;">
<h3>๐ฏ Next Steps</h3>
<ul style="list-style: none; padding: 0;">
<li>โ
Configure your database</li>
<li>โ
Set up background jobs</li>
<li>โ
Configure caching</li>
<li>โ
Deploy to production</li>
</ul>
</div>
</div>
EOF
# Creates an informative welcome page
๐ Database Configuration
Letโs set up PostgreSQL for our Rails application! ๐๏ธ
# Install PostgreSQL
sudo dnf install -y postgresql postgresql-server postgresql-contrib
# Installs PostgreSQL database server
# Initialize the database
sudo postgresql-setup --initdb
# Creates initial database cluster
# Enable and start PostgreSQL
sudo systemctl enable postgresql
sudo systemctl start postgresql
# Starts PostgreSQL service
# Create a database user for Rails
sudo -u postgres psql << EOF
CREATE USER rails_user WITH PASSWORD 'SecurePassword123!';
ALTER USER rails_user CREATEDB;
\q
EOF
# Creates a database user with permissions
# Configure PostgreSQL authentication
sudo sed -i 's/local all all peer/local all all md5/' /var/lib/pgsql/data/pg_hba.conf
# Allows password authentication
# Restart PostgreSQL
sudo systemctl restart postgresql
# Applies authentication changes
Now configure Rails database settings:
# Create database configuration
cat > config/database.yml << 'EOF'
default: &default
adapter: postgresql
encoding: unicode
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
username: rails_user
password: SecurePassword123!
host: localhost
development:
<<: *default
database: myapp_development
test:
<<: *default
database: myapp_test
production:
<<: *default
database: myapp_production
username: <%= ENV['DATABASE_USERNAME'] %>
password: <%= ENV['DATABASE_PASSWORD'] %>
host: <%= ENV['DATABASE_HOST'] %>
EOF
# Configures database connections for all environments
# Create and migrate the database
rails db:create
rails db:migrate
# Creates database and runs migrations
# Seed the database (optional)
rails db:seed
# Populates database with initial data
โ Setting Up Puma Web Server
Puma is Railsโ default high-performance web server! ๐
# Configure Puma for production
cat > config/puma.rb << 'EOF'
# Puma configuration file
# Number of threads
max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count }
threads min_threads_count, max_threads_count
# Port and environment
port ENV.fetch("PORT") { 3000 }
environment ENV.fetch("RAILS_ENV") { "production" }
# Number of workers (processes)
workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# Preload application for better performance
preload_app!
# Worker timeout
worker_timeout 30
# Allow puma to be restarted by rails restart command
plugin :tmp_restart
# Logging
stdout_redirect '/var/log/puma/access.log', '/var/log/puma/error.log', true
# Bind to unix socket for Nginx
bind "unix:///var/run/puma.sock"
# Daemonize the server
daemonize true
# Set master PID and state locations
pidfile '/var/run/puma.pid'
state_path '/var/run/puma.state'
on_worker_boot do
# Reconnect to database
ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
end
EOF
# This configures Puma for production use
# Create Puma directories
sudo mkdir -p /var/log/puma /var/run
sudo chown -R $USER:$USER /var/log/puma
# Creates directories for Puma logs and sockets
๐ฎ Quick Examples
Letโs practice with real Rails deployment scenarios! ๐ฏ
Example 1: Systemd Service for Rails
# Create systemd service for Rails app
sudo cat > /etc/systemd/system/rails-app.service << 'EOF'
[Unit]
Description=Rails Application Server
After=network.target postgresql.service
Requires=postgresql.service
[Service]
Type=simple
User=deploy
Group=deploy
WorkingDirectory=/home/deploy/myapp
Environment="RAILS_ENV=production"
Environment="RAILS_MASTER_KEY=your-master-key-here"
# Start command
ExecStart=/home/deploy/.rbenv/shims/bundle exec puma -C config/puma.rb
# Restart policy
Restart=always
RestartSec=3
# Output to journal
StandardOutput=journal
StandardError=journal
SyslogIdentifier=rails-app
[Install]
WantedBy=multi-user.target
EOF
# Enable and start the service
sudo systemctl daemon-reload
sudo systemctl enable rails-app
sudo systemctl start rails-app
# Check service status
sudo systemctl status rails-app
# Shows if Rails app is running properly
Example 2: Nginx Reverse Proxy Setup
# Install Nginx
sudo dnf install -y nginx
# Create Nginx configuration for Rails
sudo cat > /etc/nginx/conf.d/rails-app.conf << 'EOF'
upstream rails_app {
server unix:///var/run/puma.sock fail_timeout=0;
}
server {
listen 80;
server_name your-domain.com;
root /home/deploy/myapp/public;
# Logs
access_log /var/log/nginx/rails_access.log;
error_log /var/log/nginx/rails_error.log;
# Serve static files
location ~ ^/(assets|packs|images|javascripts|stylesheets|system)/ {
gzip_static on;
expires max;
add_header Cache-Control public;
add_header ETag "";
}
# Proxy to Rails app
location / {
try_files $uri @rails_app;
}
location @rails_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://rails_app;
# WebSocket support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
}
EOF
# Test and restart Nginx
sudo nginx -t
sudo systemctl restart nginx
# Applies Nginx configuration
Example 3: Background Jobs with Sidekiq
# Install Redis for Sidekiq
sudo dnf install -y redis
sudo systemctl enable redis
sudo systemctl start redis
# Configure Sidekiq
cat > config/sidekiq.yml << 'EOF'
:concurrency: 5
:max_retries: 3
:timeout: 60
:queues:
- default
- mailers
- critical
production:
:concurrency: 10
development:
:concurrency: 3
:redis:
url: redis://localhost:6379/0
EOF
# Create a Sidekiq service
sudo cat > /etc/systemd/system/sidekiq.service << 'EOF'
[Unit]
Description=Sidekiq Background Jobs
After=network.target redis.service
Requires=redis.service
[Service]
Type=simple
User=deploy
Group=deploy
WorkingDirectory=/home/deploy/myapp
Environment="RAILS_ENV=production"
ExecStart=/home/deploy/.rbenv/shims/bundle exec sidekiq -C config/sidekiq.yml
Restart=always
RestartSec=3
StandardOutput=journal
StandardError=journal
SyslogIdentifier=sidekiq
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable sidekiq
sudo systemctl start sidekiq
# Starts Sidekiq background job processor
๐จ Fix Common Problems
Encountering issues? Donโt worry! Here are solutions:
Problem 1: Assets Not Compiling
# Precompile assets manually
RAILS_ENV=production rails assets:precompile
# Compiles all CSS, JavaScript, and image assets
# Clean and recompile if needed
rails assets:clobber
RAILS_ENV=production rails assets:precompile
# Check for missing Node modules
yarn install --check-files
# Ensures all JavaScript dependencies are installed
# Fix permissions
sudo chown -R deploy:deploy public/assets
# Ensures web server can read compiled assets
Problem 2: Database Connection Errors
# Test database connection
rails db:version
# Shows database version if connected
# Check PostgreSQL is running
sudo systemctl status postgresql
# Should show "active (running)"
# Verify database exists
sudo -u postgres psql -l | grep myapp
# Lists databases matching your app name
# Reset database if needed
RAILS_ENV=production rails db:drop db:create db:migrate
# Recreates database from scratch (WARNING: data loss!)
# Check database credentials
rails console
> ActiveRecord::Base.connection.execute("SELECT 1")
# Tests database connection from Rails
Problem 3: Secret Key Base Missing
# Generate a new secret key
rails secret
# Generates a secure random key
# Set the secret key base
export SECRET_KEY_BASE=$(rails secret)
# Sets environment variable
# Or use Rails credentials
EDITOR=nano rails credentials:edit
# Opens encrypted credentials file for editing
# Add to production environment
echo "SECRET_KEY_BASE=$(rails secret)" >> .env.production
# Saves to environment file
Problem 4: Permission Denied Errors
# Fix directory permissions
sudo chown -R deploy:deploy /home/deploy/myapp
# Changes ownership to deploy user
# Fix socket permissions
sudo chmod 755 /var/run
sudo chown deploy:deploy /var/run/puma.sock
# Fix log permissions
sudo chown -R deploy:deploy /var/log/puma
sudo chmod 755 /var/log/puma
# SELinux issues (if enabled)
sudo setsebool -P httpd_can_network_connect 1
# Allows Nginx to connect to Rails
Problem 5: Memory Issues
# Check memory usage
free -h
# Shows available memory
# Reduce Puma workers if low on memory
# Edit config/puma.rb
workers ENV.fetch("WEB_CONCURRENCY") { 1 }
# Reduces to 1 worker process
# Add swap space if needed
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
# Creates 2GB swap file
# Monitor Rails memory usage
ps aux | grep puma
# Shows memory used by Puma processes
๐ Simple Commands Summary
Hereโs your Rails deployment quick reference! ๐
Command | Purpose | Example |
---|---|---|
rails server | Start development server | rails s -b 0.0.0.0 |
rails console | Open Rails console | rails c production |
rails db:migrate | Run database migrations | RAILS_ENV=production rails db:migrate |
rails assets:precompile | Compile assets | RAILS_ENV=production rails assets:precompile |
bundle install | Install gems | bundle install --deployment |
rails routes | Show all routes | rails routes | grep users |
rails db:seed | Load seed data | RAILS_ENV=production rails db:seed |
systemctl status rails-app | Check app status | Shows if Rails is running |
๐ก Tips for Success
Follow these best practices for bulletproof Rails deployments! ๐
๐ Use Environment Variables
- Never commit secrets to version control
- Use Rails credentials or dotenv gem
- Keep production configs separate
๐ง Optimize for Production
- Enable caching in production
- Use CDN for assets
- Configure proper log rotation
๐ Monitor Everything
- Set up application monitoring (New Relic, Scout)
- Monitor server resources
- Track response times and errors
๐ก๏ธ Security First
- Keep Rails and gems updated
- Use strong parameters
- Enable CSRF protection
- Implement rate limiting
โก Performance Optimization
- Use database indexes wisely
- Implement fragment caching
- Optimize database queries (N+1)
- Use background jobs for heavy tasks
๐ Deployment Best Practices
- Use zero-downtime deployments
- Automate with Capistrano or similar
- Always backup before deploying
- Test in staging first
๐ What You Learned
Congratulations! Youโve mastered Ruby on Rails deployment on AlmaLinux! ๐ Hereโs what you accomplished:
โ
Installed Ruby and Rails with rbenv version management
โ
Created and configured a production-ready Rails application
โ
Set up PostgreSQL database with proper authentication
โ
Configured Puma web server for high performance
โ
Implemented Nginx reverse proxy for production serving
โ
Set up background jobs with Sidekiq and Redis
โ
Created systemd services for automatic startup
โ
Solved common deployment issues like a pro
๐ฏ Why This Matters
Ruby on Rails isnโt just a framework - itโs a philosophy of developer happiness and productivity that has revolutionized web development! ๐
In todayโs fast-paced startup world, the ability to rapidly build and deploy robust applications is invaluable. Rails gives you superpowers to go from idea to production in record time. By mastering Rails deployment on AlmaLinux, youโre joining an elite group of developers who build the applications that power modern businesses.
Whether youโre building the next unicorn startup, creating enterprise applications, or freelancing for clients, these Rails deployment skills will accelerate your career and enable you to build amazing things that impact millions of users! ๐
Remember: Rails is optimized for programmer happiness. Keep learning, keep building, and most importantly, enjoy the journey! Every Rails application you deploy makes the web a more interesting place! โญ
Great job on completing this comprehensive Rails deployment guide! Youโre now ready to deploy production Rails applications that scale from zero to millions of users! ๐