# Production Rails Stack

> Production Ruby on Rails with Nginx, Puma, PostgreSQL, Redis, and Sidekiq for background jobs

- Category: Full Web Stacks
- Difficulty: advanced
- Components: nginx, rails, puma, postgres, redis, sidekiq
- Tags: rails, ruby, production, sidekiq, nginx, postgres, redis
- Source: https://docker.recipes/full-stacks/production-rails-stack

## Overview

NGINX is a high-performance web server and reverse proxy that has become the de facto standard for production web applications due to its event-driven architecture and exceptional performance under load. Originally developed by Igor Sysoev in 2004 to solve the C10K problem, NGINX excels at handling thousands of concurrent connections with minimal memory overhead, making it ideal for serving as a front-end proxy to Ruby on Rails applications running on Puma.

This production Rails stack combines NGINX's high-performance request handling with Ruby on Rails running on Puma application servers, backed by PostgreSQL for reliable ACID-compliant data storage and Redis for caching and job queuing. Sidekiq leverages Redis to process background jobs asynchronously, while NGINX handles static asset serving and load balancing to Puma workers. This architecture separates concerns effectively: NGINX handles the heavy lifting of HTTP connections and static files, Puma serves dynamic Rails content, PostgreSQL ensures data integrity, and Redis provides fast session storage and job queuing.

This stack is ideal for Rails applications that have outgrown simple development setups and need production-grade performance, reliability, and scalability. Startups moving from prototype to production, established companies running customer-facing Rails applications, and development teams requiring a battle-tested deployment architecture will benefit from this configuration. The combination provides the reliability needed for business-critical applications while maintaining the flexibility to scale horizontally by adding more Puma workers or Redis instances as traffic grows.

## Features

- Event-driven NGINX architecture handling thousands of concurrent connections with minimal memory usage
- Puma multi-threaded, multi-process application server optimized for Rails concurrency model
- PostgreSQL ACID compliance with advanced transaction support and JSON/JSONB document capabilities
- Redis sub-millisecond response times for session storage, caching, and Sidekiq job queues
- Sidekiq reliable background job processing with retry logic and job scheduling
- NGINX reverse proxy with load balancing across multiple Puma workers
- PostgreSQL logical replication and streaming replication for high availability
- Redis Pub/Sub messaging for real-time features and inter-service communication

## Use cases

- E-commerce platforms requiring reliable transaction processing and background order fulfillment
- SaaS applications with user authentication, session management, and async email processing
- Content management systems serving high traffic with efficient static asset delivery
- API-first applications requiring fast response times and background data processing
- Multi-tenant Rails applications with complex database queries and real-time notifications
- Enterprise applications requiring audit trails, data integrity, and scheduled job processing
- Rails applications with image processing, email delivery, and third-party API integrations

## Prerequisites

- Minimum 2GB RAM for the full stack (PostgreSQL 1GB, Redis 512MB, Rails/Puma 512MB)
- Valid RAILS_MASTER_KEY for Rails credentials and encrypted configuration
- Ruby Dockerfile with bundler, Rails dependencies, and production gems installed
- Puma configuration file (config/puma.rb) with worker and thread settings for production
- NGINX configuration with upstream Puma servers and static asset serving rules
- Understanding of Rails asset pipeline, database migrations, and Sidekiq job classes

## docker-compose.yml

```yaml
services:
  nginx:
    image: nginx:alpine
    container_name: rails-nginx
    restart: unless-stopped
    ports:
      - "${NGINX_PORT:-80}:80"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./public:/app/public:ro
    depends_on:
      - web

  web:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: rails-web
    restart: unless-stopped
    command: bundle exec puma -C config/puma.rb
    volumes:
      - .:/app
      - bundle_cache:/usr/local/bundle
    environment:
      - RAILS_ENV=production
      - RAILS_MASTER_KEY=${RAILS_MASTER_KEY}
      - DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}
      - REDIS_URL=redis://redis:6379/0
    depends_on:
      - db
      - redis

  sidekiq:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: rails-sidekiq
    restart: unless-stopped
    command: bundle exec sidekiq
    volumes:
      - .:/app
      - bundle_cache:/usr/local/bundle
    environment:
      - RAILS_ENV=production
      - RAILS_MASTER_KEY=${RAILS_MASTER_KEY}
      - DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}
      - REDIS_URL=redis://redis:6379/0
    depends_on:
      - db
      - redis

  db:
    image: postgres:16-alpine
    container_name: rails-db
    restart: unless-stopped
    environment:
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}
      - POSTGRES_DB=${DB_NAME}
    volumes:
      - postgres_data:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine
    container_name: rails-redis
    restart: unless-stopped
    volumes:
      - redis_data:/data

volumes:
  postgres_data:
  redis_data:
  bundle_cache:
```

## .env

```bash
# Rails Production Stack
NGINX_PORT=80

# Rails master key (from config/master.key)
RAILS_MASTER_KEY=your-rails-master-key

# Database
DB_USER=rails
DB_PASSWORD=rails_password
DB_NAME=rails_production
```

## Usage notes

- Create Dockerfile with Ruby and Rails dependencies
- Configure puma.rb for production workers
- Run migrations: docker compose exec web rails db:migrate
- Precompile assets: docker compose exec web rails assets:precompile
- Sidekiq processes background jobs from Redis queues
- Monitor Sidekiq at /sidekiq with authentication

## Troubleshooting

- NGINX 502 Bad Gateway errors: Verify Puma is running and accessible on configured upstream port, check container networking between nginx and web services
- Sidekiq jobs not processing: Ensure Redis is accessible from sidekiq container and REDIS_URL environment variable matches Redis service configuration
- PostgreSQL connection refused: Check DATABASE_URL format includes correct credentials and that db service is fully initialized before Rails containers start
- Rails assets not loading: Verify public volume mount in nginx service and run 'docker compose exec web rails assets:precompile' in production environment
- Puma workers crashing: Increase memory allocation and check for memory leaks, review puma.rb worker and thread configuration for available resources
- Redis memory issues: Monitor Redis memory usage with 'docker compose exec redis redis-cli info memory' and configure appropriate maxmemory policies

