Deploying Rails Applications with Kamal: A Complete Guide

1 min read
Deploying Rails Applications with Kamal: A Complete Guide

Introduction to Kamal

Kamal is a deployment tool that makes it easy to deploy containerized Rails applications to any Linux server. It combines the simplicity of Capistrano with the power of Docker.

Why Kamal?

  • Zero-downtime deployments
  • Built-in SSL with Let's Encrypt
  • Simple configuration
  • No Kubernetes complexity
  • Works with any VPS provider

Initial Setup

First, install Kamal and initialize your project:

gem install kamal
kamal init

Configuration

Configure your deployment in config/deploy.yml:

# config/deploy.yml
service: myapp
image: myapp

servers:
  web:
    - 192.168.1.1

registry:
  username: myusername
  password:
    - KAMAL_REGISTRY_PASSWORD

env:
  clear:
    RAILS_LOG_TO_STDOUT: true
  secret:
    - RAILS_MASTER_KEY
    - DATABASE_URL

Dockerfile Optimization

# Multi-stage build for smaller images
FROM ruby:3.3-slim as base

FROM base as build
RUN apt-get update -qq && \\
    apt-get install --no-install-recommends -y \\
    build-essential git libpq-dev

COPY Gemfile* ./
RUN bundle install

FROM base
COPY --from=build /usr/local/bundle /usr/local/bundle
COPY . .

CMD ["./bin/rails", "server"]

Database Management

Kamal accessories make it easy to manage databases:

accessories:
  db:
    image: postgres:15
    host: 192.168.1.2
    port: 5432
    env:
      clear:
        POSTGRES_USER: myapp
      secret:
        - POSTGRES_PASSWORD

Deployment Commands

# First deployment
kamal setup

# Subsequent deployments
kamal deploy

# Rolling back
kamal rollback

# Viewing logs
kamal app logs

Monitoring and Maintenance

  • Use kamal app exec for Rails console access
  • Monitor with kamal traefik logs
  • Clean up old images with kamal prune