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
, andcapistrano-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'
Run bundle install
to install the gems.
Setting Up Capistrano
To initialize Capistrano in your project, run:
bundle exec cap install
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
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}
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)
}
Deployment Workflow Explained
Capistrano follows a series of automated steps during the deployment process:
-
Setup: Initializes the deployment structure on the server (directories like
/releases
and/shared
). - Fetch Code: Pulls the latest code from the Git repository.
-
Install Dependencies: Uses Bundler to install Ruby gems (
bundle install
). -
Run Migrations: Executes
rake db:migrate
to update the database schema. -
Precompile Assets: Runs
rake assets:precompile
for Rails applications. - Restart Server: Restarts the application server (e.g., Passenger or Puma).
- Cleanup: Removes old releases to free up disk space.
To deploy your application, run:
bundle exec cap production deploy
Rolling Back a Deployment
If something goes wrong, you can quickly roll back to the previous release:
bundle exec cap production deploy:rollback
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'
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'
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'
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
2. Permission Errors
If you encounter permission errors, adjust the permissions of the deployment directory:
sudo chown -R deploy:deploy /var/www/my_app
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
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!
Top comments (0)