Capistrano simplifies many of the common tasks encountered when to deploying an app to one or more servers, allowing a push with a simple cap deploy. Along with Ruby apps, it can be used to deploy static (HTML) pages. The nice thing about using Capistrano rather than something such as rsync is that we can easily pull the latest version from a git repository, as well as rollback to a previous version.

I will assume that our VPS has been set up as in my VPS setup post, but the essentials are:

SSH access

Ruby

A server (nginx, Apache, …)

A git repository for the app

So, nothing extraordinary.

We’ll be deploying a Sinatra application. As an example, we’ll quickly create a “Hello World!” app and then get it working on the server. Although we’ll deploy a Sinatra app to demonstrate the process, but it extends trivially to other Ruby apps.

Local Setup

Let’s create a directory to hold our app, create the Gemfile and install the required gems.

The echo is creating a .gitignore file which tells git which files and folders to ignore; we don’t need to track the .bundle directory. We git add all the files to the staging area and then commit them with a message.

In order for Capistrano to deploy our app, we’ll tell it to use git. This means setting up a remote repository, which GitHub provides for free. Create a new repository on GitHub and add the remote repo to our local one, then push to it.

Our ‘app’ now exists locally and remotely. When we makes changes locally, we git commit the changes and the git push them to GitHub. Each commit effectively acts as a separate release which Capistrano can deploy.

The -a flag adds all modified files, which in this case is the Gemfile and the lock fileGemfile.lock.

Setting up Capistrano

To get our app set up with Capistrano, we need to ‘capify’ the folder. This creates two files: Capify, at the root of the app; and deploy.rb, inside a config directory.
The deploy.rb file is where almost all of the configuration is done. Rather than going through all the possible configuration options, we’ll use a template deploy file I’ve created. It’s heavily commented, make sure to understand what it’s doing. There’s a few things you’ll need to change.

:application: Whatever you like. It just determines what the app’s folder on the server is called.

We’ve now created a workflow for updating our app. The procedure in this article is very similar no matter what Ruby application your deploying. For apps that talk to a database, you’ll just need to create the database on the server before the cold deploy.

The advantage with this approach is git management, and for future GitHub-hosted apps we won’t have to log in to the VPS at all. We can also deploy HTML apps this way, just place all files that need to have public access inside a public directory, then capify the app as normal.