This is one of those things that we all kinda know but that it’s good to write down – how to deploy static files using rsync. For purposes of illustration, this article will describe how to deploy a statically generated website.
In the following discussion, you can assume that the static site resides at a directory local the script. Using rsync, it’s a simple command to turn your server into an exact copy of your local file system.
#!/bin/bash
set -o nounset
set -o errexit
NFLAG=""
while getopts ":n" opt; do
case $opt in
n)
NFLAG="-n"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
;;
esac
done
# Set the environment by loading from the file "environment" in the same directory
DIR="$( cd "$( dirname $( dirname "$0" ) )" && pwd)"
source "$DIR/.env"
echo "Deploying ${DIR}/${DEPLOY_SOURCE_DIR} to ${DEPLOY_ACCOUNT}@${DEPLOY_SERVER}:${DEPLOY_DEST_DIR}"
chmod -R og+Xr ${DIR}/${DEPLOY_SOURCE_DIR}
rsync $NFLAG -rvzp --delete --exclude-from="$DIR/.deployignore" "${DIR}/${DEPLOY_SOURCE_DIR}" "${DEPLOY_ACCOUNT}@${DEPLOY_SERVER}:${DEPLOY_DEST_DIR}"
The script uses the -n
option, represented as the NFLAG
bash variable,
to do a dry run of your rsync command. This shows the list of files that
would be affected by the command, yet does not transfer any data.
The script is general purpose and takes advantage of a .env
file that
you would write. The .env
file declares the source directory you wish to
copy files from ($DEPLOY_SOURCE_DIR
), the account name to deploy with
($DEPLOY_ACCOUNT
), the server to deploy to ($DEPLOY_SERVER
), and the
destination directory to copy files to on the server ($DEPLOY_DEST_DIR
).
The rsync command uses the --delete
option to remove any files from the
server that no longer exist on the local filesystem and the
--exclude-from
option to ignore any files listed in the .deployignore
file that you would declare. The command is also recursive (-r
), verbose
(-r
), compressed (-z
), and preserves file permissions (-p
).