Deploying Ruby on Rails Apps with Docker: A Practical Guide

Deploying Ruby on Rails applications can be complex, but using Docker simplifies the process significantly. Docker allows developers to containerize their applications, ensuring consistency across different environments and streamlining deployment workflows.

Introduction to Docker and Ruby on Rails

Ruby on Rails is a popular web application framework written in Ruby, known for its convention over configuration approach. Docker, on the other hand, is a platform that enables developers to package applications and their dependencies into containers. Combining these tools provides a robust environment for development, testing, and deployment.

Prerequisites

  • Basic knowledge of Ruby on Rails development
  • Docker installed on your machine
  • Access to a terminal or command line interface
  • A Rails application ready for deployment

Creating a Dockerfile for Rails

Start by creating a Dockerfile in the root directory of your Rails project. This file defines the environment in which your application will run.

FROM ruby:3.2.0

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

# Set working directory
WORKDIR /app

# Copy Gemfile and Gemfile.lock
COPY Gemfile Gemfile.lock ./

# Install gems
RUN bundle install

# Copy the rest of the application
COPY . .

# Precompile assets
RUN bundle exec rake assets:precompile

# Expose port 3000
EXPOSE 3000

# Start the server
CMD ["rails", "server", "-b", "0.0.0.0"]

Configuring Docker Compose

Docker Compose simplifies managing multi-container applications. Create a docker-compose.yml file to define your Rails app and database services.

version: '3.8'

services:
  db:
    image: postgres:13
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password
      POSTGRES_DB: myapp_development
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data

  web:
    build: .
    command: rails server -b 0.0.0.0
    volumes:
      - .:/app
    ports:
      - "3000:3000"
    depends_on:
      - db
    environment:
      DATABASE_URL: postgres://postgres:password@db:5432/myapp_development

volumes:
  pgdata:

Building and Running the Application

Use Docker commands to build and run your Rails application. From the project directory, execute:

docker-compose build
docker-compose up

Visit http://localhost:3000 in your browser to see your Rails app running inside Docker.

Additional Tips for Deployment

  • Use environment variables to manage sensitive data.
  • Optimize Dockerfile for production by multi-stage builds.
  • Integrate with CI/CD pipelines for automated deployment.
  • Use Docker volumes to persist data and logs.

Containerizing your Rails application with Docker enhances portability, consistency, and scalability. With these steps, you can streamline your deployment process and focus on developing features.