Capistrano: The Ultimate Guide to Automated Deployments for Rails Applications

sparsh9

Sparsh Garg

Posted on November 13, 2024

Capistrano: The Ultimate Guide to Automated Deployments for Rails Applications

Deploying web applications manually can be a time-consuming and error-prone process. This is where Capistrano comes into play — a powerful Ruby-based tool designed to automate and simplify the deployment of web applications. In this comprehensive guide, we’ll explore what Capistrano is, how it works, its key features, and provide a step-by-step tutorial with practical examples to help you set it up for your Ruby on Rails application.

What is Capistrano?

Capistrano is an open-source tool for automating the deployment of web applications to remote servers via SSH. It streamlines repetitive tasks such as code fetching, dependency installation, database migrations, and server restarts, making the deployment process fast, reliable, and consistent.

Key Features of Capistrano:

  • Automated Deployment: Reduces human error by automating repetitive deployment tasks.
  • Multi-server Support: Easily deploys applications across multiple servers and roles (e.g., web, app, db).
  • Rollbacks: Allows you to quickly revert to previous releases in case of deployment failures.
  • Customizable Tasks: Provides flexibility to define custom tasks tailored to your application needs.
  • Integration with Popular Tools: Supports plugins like capistrano-rails, capistrano-rvm, and capistrano-bundler for Rails-specific tasks and Ruby version management.

Getting Started with Capistrano

Installation

First, add Capistrano and necessary plugins to your Rails project’s Gemfile:

# Gemfile
gem 'capistrano', '~> 3.17'
gem 'capistrano-rails', '~> 1.6'
gem 'capistrano-rvm', '~> 0.2.0'
gem 'capistrano-bundler', '~> 2.0'
gem 'capistrano-passenger', '~> 0.2'
Enter fullscreen mode Exit fullscreen mode

Run bundle install to install the gems.

Setting Up Capistrano

To initialize Capistrano in your project, run:

bundle exec cap install
Enter fullscreen mode Exit fullscreen mode

This command generates the following files:

  • Capfile: The main configuration file where plugins are required.
  • config/deploy.rb: Global configuration settings for the deployment.
  • config/deploy/production.rb: Environment-specific configuration (e.g., for production).

Capistrano Configuration Files Explained

1. Capfile

The Capfile is where you require necessary libraries and plugins:

require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/rvm'
require 'capistrano/bundler'
require 'capistrano/rails'
require 'capistrano/passenger'

install_plugin Capistrano::RVM
install_plugin Capistrano::Bundler
install_plugin Capistrano::Rails::Migrations
install_plugin Capistrano::Passenger
Enter fullscreen mode Exit fullscreen mode

2. Global Configuration (config/deploy.rb)

The deploy.rb file defines the main configuration for your application:

set :application, "my_app"
set :repo_url, "git@github.com:username/my_app.git"
set :deploy_to, "/var/www/#{fetch(:application)}"
set :branch, "main"
set :format, :pretty
set :log_level, :info
set :keep_releases, 5

# RVM Configuration
set :rvm_type, :user
set :rvm_ruby_version, '2.7.8'

# Linked Files & Directories
set :linked_files, %w{config/database.yml .env}
set :linked_dirs, %w{log tmp/pids tmp/cache tmp/sockets public/system}
Enter fullscreen mode Exit fullscreen mode

3. Environment Configuration (config/deploy/production.rb)

This file specifies server details and environment-specific configurations:

server '123.45.67.89', user: 'deploy', roles: %w{app web db}, primary: true

set :rails_env, 'production'
set :ssh_options, {
  keys: %w(~/.ssh/id_rsa),
  forward_agent: true,
  auth_methods: %w(publickey)
}
Enter fullscreen mode Exit fullscreen mode

Deployment Workflow Explained

Capistrano follows a series of automated steps during the deployment process:

  1. Setup: Initializes the deployment structure on the server (directories like /releases and /shared).
  2. Fetch Code: Pulls the latest code from the Git repository.
  3. Install Dependencies: Uses Bundler to install Ruby gems (bundle install).
  4. Run Migrations: Executes rake db:migrate to update the database schema.
  5. Precompile Assets: Runs rake assets:precompile for Rails applications.
  6. Restart Server: Restarts the application server (e.g., Passenger or Puma).
  7. Cleanup: Removes old releases to free up disk space.

To deploy your application, run:

bundle exec cap production deploy
Enter fullscreen mode Exit fullscreen mode

Rolling Back a Deployment

If something goes wrong, you can quickly roll back to the previous release:

bundle exec cap production deploy:rollback
Enter fullscreen mode Exit fullscreen mode

Custom Tasks in Capistrano

Capistrano allows you to define custom tasks to fit your deployment needs. Here are some useful examples:

Example 1: Clearing Sidekiq Logs

namespace :logs do
  desc "Clear Sidekiq logs"
  task :clear_sidekiq_log do
    on roles(:app) do
      execute "echo '' > #{shared_path}/log/sidekiq.log"
      puts "Sidekiq logs cleared!"
    end
  end
end

after 'deploy:finished', 'logs:clear_sidekiq_log'
Enter fullscreen mode Exit fullscreen mode

Example 2: Update File Permissions

namespace :deploy do
  desc "Update permissions"
  task :update_permissions do
    on roles(:app) do
      execute "chmod -R 755 #{release_path}/"
      puts "Permissions updated for #{release_path}"
    end
  end
end

after 'deploy:finishing', 'deploy:update_permissions'
Enter fullscreen mode Exit fullscreen mode

Example 3: Restarting Nginx

namespace :nginx do
  desc "Restart Nginx"
  task :restart do
    on roles(:web) do
      execute "sudo systemctl restart nginx"
      puts "Nginx restarted successfully!"
    end
  end
end

after 'deploy:finishing', 'nginx:restart'
Enter fullscreen mode Exit fullscreen mode

Troubleshooting Common Issues

1. SSH Authentication Errors

Ensure your SSH key is correctly configured and added to the SSH agent:

ssh-add ~/.ssh/id_rsa
Enter fullscreen mode Exit fullscreen mode

2. Permission Errors

If you encounter permission errors, adjust the permissions of the deployment directory:

sudo chown -R deploy:deploy /var/www/my_app
Enter fullscreen mode Exit fullscreen mode

3. Git Repository Access Issues

Verify that your SSH key has access to the Git repository and SSH agent forwarding is enabled:

set :ssh_options, forward_agent: true
Enter fullscreen mode Exit fullscreen mode

Best Practices for Using Capistrano

  • Use SSH Key Forwarding: This avoids storing your private SSH key on the server.
  • Limit Release History: Use set :keep_releases, 5 to avoid filling up the server with old releases.
  • Test Deployments Locally: Use --dry-run to safely test your deployment commands without making changes.

Conclusion

Capistrano is a robust and versatile tool that can handle complex deployment scenarios with ease. By leveraging its automation capabilities, you can save time, reduce human errors, and focus more on building features rather than managing deployments. With proper configuration and custom tasks, Capistrano can fit seamlessly into your DevOps workflow, making your deployments reliable and efficient.

Start using Capistrano today and take your deployment process to the next level. 🚀

Happy deploying!

💖 💪 🙅 🚩
sparsh9
Sparsh Garg

Posted on November 13, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related