Containerizing Ruby on Rails Applications with Docker for Production Deployment

Deploying Ruby on Rails applications to production can be complex due to dependencies, environment configurations, and server setup. Containerization with Docker simplifies this process by creating isolated, reproducible environments. This article explores how to containerize a Rails app using Docker for seamless production deployment.

Why Containerize Ruby on Rails Applications?

Containerizing Rails applications offers numerous benefits:

  • Consistency: Ensures the app runs the same way across development, staging, and production.
  • Scalability: Easily scale containers to handle increased traffic.
  • Isolation: Avoid conflicts with other applications and dependencies on the server.
  • Portability: Move applications between environments without modification.

Setting Up Docker for a Rails Application

To containerize a Rails app, start by creating a Dockerfile that defines the environment. This file specifies the base image, dependencies, and commands to run the app.

Sample Dockerfile

Below is an example Dockerfile for a Rails application:

FROM ruby:3.1.0

# Install dependencies
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client

# Set working directory
WORKDIR /app

# Add Gemfile and install gems
COPY Gemfile* /app/
RUN bundle install

# Copy the rest of the application code
COPY . /app

# Precompile assets
RUN RAILS_ENV=production bundle exec rails assets:precompile

# Expose port 3000
EXPOSE 3000

# Start the server
CMD ["bundle", "exec", "puma", "-C", "config/puma.rb"]

Configuring Docker Compose for Multi-Container Setup

For production, it’s common to use Docker Compose to manage multiple containers, such as the Rails app and the database. Here’s an example docker-compose.yml file:

version: '3.8'

services:
  db:
    image: postgres:13
    environment:
      POSTGRES_USER: railsuser
      POSTGRES_PASSWORD: password
      POSTGRES_DB: railsapp_production
    volumes:
      - db_data:/var/lib/postgresql/data

  web:
    build: .
    ports:
      - "3000:3000"
    environment:
      DATABASE_URL: postgres://railsuser:password@db:5432/railsapp_production
    depends_on:
      - db

volumes:
  db_data:

Deploying to Production

Once configured, build and run your containers:

docker-compose build
docker-compose up -d

Ensure your server environment supports Docker and Docker Compose. You can then access your Rails app via the server’s IP address on port 3000.

Conclusion

Containerizing Ruby on Rails applications with Docker streamlines deployment, enhances consistency, and simplifies scaling. By creating a Dockerfile and using Docker Compose, developers can efficiently move their Rails apps into production environments with confidence.