Using Git Hooks for Continuous Integration on Live Production Server
15 Aug 2021
This article is about to set up Git Hooks for Continuous Integration on live production server.
Live Production Server Setup
Live directory:
/home/yourusername/liveproductionapps
Repo directory:
/home/yourusername/liveproductionrepository.git
Create Repository
First thing first, you need to login to your production server using SSH method and then type this command:
mkdir repository && cd repository
mkdir liveproductionrepository.git && cd liveproductionrepository.git
git init --bare
'--bare'
means that the liveproductionrepository folder will have no source files, just the version control.
Hooks
Inside liveproductionrepository.git (Git repositories) have a folder called 'hooks'. This folder contains some sample files for possible actions that you can hook and perform custom actions set by you. You can read more documentation about Hook on Git Documentation, because on this tutorial I will straight forward to set up Continous Integration on production server.
In liveproductionrepository.git, you can find 'hooks' folder and you can change directory to the 'hooks' folder by typing:
cd hooks
Now, create a file 'post-receive'. The 'post-receive' file will be looked into every time a push is completed and it's saying that your files need to be in /home/yourusername/liveproductionapps
vim post-receive
After that, set the directory that we want to set up for Continous Integration
#!/bin/sh
git --work-tree=/home/yourusername/repository/liveproductionapps \
--git-dir=/home/yourusername/repository/liveproductionrepository.git checkout -f
Save it
:wq
And make it executable
chmod +x post-receive
Local Machine Setup
First quit from the server by typing:
exit
Go to your project directory, for example:
cd myproject
Then:
git init
After that we need to configure the remote path of our repository. Tell Git to add a remote called 'origin:
git remote add origin ssh://user@mydomain.com/home/yourusername/repository/liveproductionrepository.git
Let's assume that you already have project ready in this folder. We should do the usual git steps of adding the files and commit with a message:
git add .
git commit -m "first push for CI"
To finish everything, just push it by typing:
git push origin main
Counting objects: 10, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (10/10), done.
Writing objects: 100% (10/10), 10.56 KiB, done.
Total 10 (delta 0), reused 0 (delta 0)
To ssh://user@mydomain.com/home/yourusername/repository/liveproductionrepo.git*
[new branch] main -> main
Now the setup is done and you can push your development project from local machine to the live production server.