Hi, I’m Nico Hagenburger
I enjoy designing
clean, simple websites,
developing living style guides
& increasing usability.

How to auto deploy Rails apps after Git push

For my most recent project, I had to share a git repository with another Rails developer. He also had to make deploys on my server. As my server has many projects, I though about having another way than giving him access via SSH for cap deploy.

I remembered Heroku automatically deploys Rails apps after commits. So here’s how you can have the same functionality with pure Git.

Configuration of SSH And Users

I’m assuming the following configuration:

Git repository
/home/git/awesome-rails-app.git
Deploy path
/var/www/awesome-rails-app
Git user
git
Deploy user
deploy
Authentication
with SSH keys

First, create a SSH key for the user git (unless you already did so) and add it for for the deploy user and vice versa:

# log in as git:
ssh-keygen -t rsa
# log in as deploy:
cat /home/git/.ssh/id_rsa.pub >> /home/deploy/authorized_keys
ssh-keygen -t rsa
# log in as git:
cat /home/deploy/.ssh/id_rsa.pub >> /home/git/authorized_keys

Installing the Git Hook

Git offers some hooks, where you can add your own code. The most interestion hook for having a deploy is “post-receive”. Just add the deploy command:

# File: /home/git/awesome-rails-app.git/hooks/post-receive
#!/bin/sh

cd /var/www/awesome-rails-app/current && cap deploy:migrations

## If Git isn’t on the same server as the application:
# ssh deploy@deploy-server.com \
#   'cd /var/www/awesome-rails-app/current && cap deploy:migrations'
## Don’t forget to add the SSH keys.

Make this file executable:

chmod +x /home/git/awesome-rails-app.git/hooks/post-receive

Finish

Now it should work (on your local mashine):

git push origin master

You’ll see all commands of the cap deploy:migrations process in your console.

This post was inspired by this post. After you finished the automatical deploy, there is some other interesting homework: auto test before commits, integration your bug tracker, ...