Using Git Hooks to Push Code to Production
Here's a handy git hook script to be able to push your master branch to a remote server and deploy it with ease.
SSH into your server:
ssh <usermame>@<server-ip>
Create deploy folder:
mkdir ~/deploy-folder
Add a bare git repo for our hooks:
git init --bare ~/project.git
Add a post-receive file and make it executable:
touch ~/project.git/hooks/postreceive
chmod +x ~/project.git/hooks/post-receive
This post-receive file should contain:
#!/bin/bash
set -eu
TARGET="$HOME/deploy-folder"
GIT_DIR="$HOME/project.git"
BRANCH="master"
while read oldrev newrev ref
do
# only checking out the master (or whatever branch you would like to deploy)
if [[ $ref = refs/heads/"$BRANCH" ]];
then
echo "Ref $ref received. Deploying ${BRANCH} branch to production..."
git --work-tree="$TARGET" --git-dir="$GIT_DIR" checkout -f
else
echo "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."
fi
done
Now we have the server set to receive the branch, we can add the remote on our local machine:
cd ~/path/to/working-copy/
git remote add production demo@yourserver.com:project.git
We can now push our master branch to the production server via:
git push production master
And done, assuming you have your server set up to serve the files from the directory you just pushed to, you can deploy your code with one command!