Imagine you have a local server where you work on developing the code for a web application. After doing your magic, you want to upload it to the web server so the rest of the world can access your shiny new web app. To do that, you have to place your code on another server, which serves as the production environment. Moreover, when making changes to your code, you only want to update the modified files, not everything.
You could keep track of what files have been changed on your dev server, and then manually transfer them to the web server in production. Now that we have established how much time and sanity you would lose, especially with a big app, let’s see how Git can make this kind of code deployment not only possible, but also smooth and efficient.
I will be using the root account for this demo, which is of course a bad idea in a live environment, so keep that in mind =D
On the server side, say we have a folder named Prod. Here we will push the code for a website, and then we’ll transfer it to the web directory.
First, initialize a bare repository inside the Prod folder:
1 2 |
|
For better security, we’ll keep the git repository outside the web root directory. To automatically update the code, we’ll use a git hook, which is a script that runs when a certain event occurs. In this case, we’ll create a post-receive
hook, which runs on a remote repository after a git push
In the hooks directory, I created a hook called post-receive, with the following code in it:
1 2 |
|
Looking inside the hooks directory, you will see the samples are executable. We also have to make ours executable, so use chmod +x
With that, the production server setup is complete. On the local development server, make a repository and add some files that you want to end up in production:
1 2 3 4 5 6 7 8 9 10 11 |
|
Now add a remote, which will point to the production repository:
1
|
|
Make a commit:
1 2 3 4 5 |
|
And now push the changes to production — note the use of the refspec:
1 2 3 4 5 6 7 8 |
|
Let’s see if it worked! On my production server:
It did work! Now let’s update a file, and only push this file which has been modified. After making the modifications, look at the current status:
1 2 3 4 5 6 7 8 9 |
|
Commit the modified file:
1
|
|
And now push to production and also set the remote branch so next time you can do it with a simple git push production
:
1 2 3 4 5 6 7 8 9 |
|
And to confirm that on the production environment, only the modified file was updated, but the unchanged one remained the same:
1 2 3 4 5 6 |
|
It might not look like much for the 2 small files I have here, but in a huge code environment, you will feel the difference!
1 2 3 4 5 6 7 8 9 |
|