@yamilurbina

Web and mobile developer, soon-to-be entrepreneur and startup maker.


Facebook
LinkedIn
Twitter

June 14, 2012 at 10:54pm
Home

Manage your websites in the cloud using Git

Back in the day (yes, I said that) if you had to update changes to your websites, you connected via FTP to the server, uploaded your files and opened a browser window to check if nothing was broken.

Let’s call this method ‘old school’. It worked and still works nowadays, but with the arriving of cloud machines, you get absolute control of your server, including how to deploy and update code. This is where git comes in handy, as a way to keep your websites under version control and also as a deploy tool with a simple git push.

Requirements

You need the following tools:

  • Git
  • SSH access to your server
  • A website under version control in your local machine

Let’s start

Alrighty, log in to your server via SSH, copy and paste the following:

mkdir myrepositoy.git
cd myrepository.git
git init --bare

What we just did is create an empty repository. This will act as a intermediary between your local machine code and your website code (NOTICE THE .GIT AT THE END). To make this easy to understand, imagine this is a GitHub repository that we will use as a main source of code.

On your local machine

Now browse to your website folder in your local machine that’s under version control. Type in the following:

git remote add web username@website.com:myrepository.git
git config --global remote.origin.receivepack "git receive-pack"
git push web master

What we just did? Well, we added a remote repository, which is the one we created some paragraphs away. After that, we pushed our source code to the repository in our server.

On your server

Back in the server, let’s create a new folder with the name of our website:

mkdir mywebsite

Now, we need to find a way to update this folder everytime we push the code to the server. To do this, we use git hooks:

cd myrepository.git
cd hooks

Now edit post-receive with your favorite editor:

#!/bin/sh
GIT_WORK_TREE=/path/to/folder/mywebsite git checkout -f

Close your editor. There’s one thing left to do:

chmod +x hooks/post-receive

Wait, what? Ok, let me explain. We browsed to the repository created at the beginning, then we edited the post-receive file located at hooks/. Everytime there’s a push to this repo, the mywebsite folder will checkout the contents of the repository, basically cloning what’s in there. The chmod part is to make the post-receive file executable by our server.

Wrapping up

Now try pushing updated code to the repository. Open your website and you’ll see the changes you made. Forget about ftp, and the benefits of using version control beats any other method, since you can roll to previous versions of your website, in case there was an error.

Questions?

You can always reach me on twitter @yamilurbina or Google plus