Step 1: Add a git repository somewhere in your server
Create a blank git repository somewhere in your server. For example, see the following code
cd /path/to/your/folder git --bare init myrepo.git
You will see that a new directory named myrepo.git has been created. Inside that folder you will find a few other folders named “hooks”, “branches” and so on. However, sometime, this command may give you unexpected result by creating those child folders outside the myrepo.git. In that case the following commands are helpful
cd /path/to/your/folder mkdir myrepo.git cd myrepo.git git --bare init
Now everything will be inside this myrepo.git folder. Lets move to the next step.
Step 2: Add this newly created git repo as a remote to your current project
This part is easy, just follow these commands from inside your current project. We are going to add the repository we created in step 1 as a remote named “server”
cd /your/current/project/directory git remote add server ssh://user@serveraddress/path/to/your/folder/myrepo.git
Once added, you can push to this git repo like you did with origin, like
git commit -am "Some Commit Message" git push server master # (or simply git push server)
You may want to add your local machine’s public key in the ~/.ssh/authorized_keys file so that you won’t have to input username and password every time you push your code.
Step 3: Add the git hook
To deploy your code after a push, we need to deal with post-receive hook. Log into your remote server and go to the repository that we had created in step 1 (i.e /path/to/your/folder/myrepo.git). Now go to the hooks directory and create a file named post-receive. If you want to deploy your code to a directory accessible by web server, for example /usr/share/nginx/www/myproject then the code of post-receive will be like this
#!/bin/bash export GIT_WORK_TREE=/usr/share/nginx/www/myproject git checkout -f
The code above will checkout current HEAD of master branch inside the directory specified by GIT_WORK_TREE. But sometime, you may have another project which is cloned from your git repo. In those directories, instead of checking out, we will do a git pull. So our post-receive file’s code will be like this
#!/bin/bash cd /usr/share/nginx/www/myproject unset GIT_DIR git pull
remember to unset GIT_DIR which is very important for a git pull from post-receive hook.
Step 4: Give the executable permission to this post-receive hook
In this last step, just give executable permission to this post-receive file and you’re done
chmod +x /path/to/your/folder/myrepo.git/hooks/post-receive
That’s mainly it 🙂 Now whenever you push your code from local machine to this remote git repository, your code will be deployed instantly.
I hope you’ve enjoyed this article and I would love to hear your comments.