Using git And rsync To Remote Install Code

It can be annoying to maintain a git repository on your web server and use commit hooks to install new code. Here’s a way to still use git, but instead use rsync to push those updates to the server.

Your project may look like the one below, a node server with support files:

my_project
├── .git
├── admin
├── assets
└── server
    ├── resources
    ├── server.js
    ├── static
    ├── views

Create a ‘staging‘ folder outside your project folder.

$ mkdir my_project_staging

In your favorite editor, create a new bash script to do the work for us.

# set staging folder
STAGEDIR=/home/rockstar/my_project_staging

# set your website host
HOST=example.com

# set the destination folder at your host
HOSTDIR=/home/user/my_project/server/

echo "staging locally, then syncing with server..."
GIT_WORK_TREE=${STAGEDIR}

echo "git working tree is now $GIT_WORK_TREE"
export GIT_WORK_TREE

echo "checking out to staging folder..."
git checkout -f master -- server

#echo "installing updates..."
#rsync -r -a -v -u -e "ssh -l ubuntu" --delete ${STAGEDIR}/server/ ${HOST}:${HOSTDIR}

Run this script in your git repository.

The checkout will ONLY check out the /server folder to your staging folder.

Your staging folder should look like this:

my_project_staging
└── server
    ├── resources
    ├── server.js
    ├── static
    ├── views

Run rsync to install the updates to your server

Uncomment the last two lines on the bash script if your staging folder looks correct and then execute the script again. Customize the rsync options to work with your host.

Wrap Up

The big problem with this method is that the timestamps are all NEW in your staging folder so rsyns send everything up to the server every time. I’m looking into a solution, probably using one of these methods mentioned here.

Good Luck!

Leave a Reply