Last active
April 3, 2020 15:52
-
-
Save tonylegrone/c979ab8ebf067dc7bd885d1b6587f8a8 to your computer and use it in GitHub Desktop.
Zero downtime deployment script for ubuntu nginx server on EC2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
die () { | |
echo >&2 "$@" | |
exit 1 | |
} | |
reset_opcache() { | |
sudo php /home/ubuntu/cachetool.phar opcache:reset --fcgi=/run/php/php7.4-fpm.sock | |
} | |
# this var has been manually set on the server. it's meant to avoid accidentally | |
# running this script on someone's local machine. | |
[ "$IS_EC2_SERVER" -eq 1 ] || die 'Refusing to run on non EC2 server' | |
# set vars | |
BUILD_PATH=/home/ubuntu/builds | |
LAST_SUCCESS_FILE=/home/ubuntu/.deploy_last_success | |
LAST_SUCCESS_BUILD=$(cat $LAST_SUCCESS_FILE) | |
TIMESTAMP=$(date +"%Y%m%d%H%M%S") | |
# if a build folder name is provided, we can revert back to it | |
if [ "$#" -eq 1 ]; then | |
# re-install old build | |
TIMESTAMP=$1 | |
else | |
# new deployments are uploaded by the CI server here: $BUILD_PATH/new | |
# then we rename it to the current $TIMESTAMP. | |
mv "$BUILD_PATH/new" "$BUILD_PATH/$TIMESTAMP" | |
fi | |
sudo ln -sfn "$BUILD_PATH/$TIMESTAMP" "$BUILD_PATH/current" | |
reset_opcache | |
# try the app | |
if [[ $(curl -sL -w "%{http_code}" 127.0.0.1 -o /dev/null) == 200 ]]; then | |
# record success | |
echo "$TIMESTAMP" > $LAST_SUCCESS_FILE | |
echo "$TIMESTAMP built successfully" | |
exit 0 | |
else | |
# revert to last successful build | |
sudo ln -sfn "$BUILD_PATH/$LAST_SUCCESS_BUILD" "$BUILD_PATH/current" | |
reset_opcache | |
# delete bad build | |
rm -rf "${BUILD_PATH:?}/$TIMESTAMP" | |
die "Build failed; reverted back to $LAST_SUCCESS_BUILD" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment