Learn how to deploy code to a server by using git with post-receive hooks.
2014-01-22
This is a handy trick for pushing your code and deploying it with the same command via git.
In your git repo on your remote server there's a directory called hooks
. Create a new file in hooks called post-receive
and set it as an executable by running chmod +x post-receive
.
Now open post-receive and insert the following code:
#!/bin/sh
LOGFILE=./post-receive.log
DEPLOYDIR=$DEPLOYDIR # The place to deploy to.
echo -e "[log] Received push request at $( date +%F)" >> $LOGFILE
echo "[log] - Old SHA: $oldrev New SHA: $newrev Branch Name: $refname" >> $LOGFILE
echo "[log] Starting Deploy..." >> $LOGFILE
echo "[log] - Starting code update"
GIT_WORK_TREE="$DEPLOYDIR" git checkout -f
echo "[log] - Finished code update"
echo "[log] - Starting npm install..."
cd "$DEPLOYDIR"; npm install; cd -
echo "[log] - Finished npm install."
echo "[log] - Starting gulp build..."
cd "$DEPLOYDIR"; gulp build; cd -
echo "[log] - Finished gulp build."
echo "[log] - Building Hugo blog..."
cd "$DEPLOYDIR" && hugo
echo "[log] - Finished building hugo blog"
echo "[log] Finished Deploy" >> $LOGFILE
A few things to note:
$RCA_THEME_PATH
is an environment variable set to the absolute path to where I want my repo to checkout the code.Now, once you've added your updated code and committed it, when you run git push origin master
(replace origin with your remote name), you'll see your code change on your remote server.
For the most part, this technique is a pretty good solution for pushing code and deploying it at the same time. One major drawback is that you have to version control your distribution directory (the compiled code for your js, css and templates), which is not generally considered a good practice.
Hey, I'm Chase. I help aspiring entrepreneurs and makers turn their ideas into digital products and apps.
Subscribe to my Newsletter
Every other week I publish the Curiously Crafted newsletter.
In it, I explore the intersection of curiosity and craft: the people who make stuff, what they make and the way they pursue the craft of making.