Project: Automated Git Deploy and Rollback Script
In this project, we will build a production deployment script that pulls the latest code from Git, installs dependencies, runs a build, and automatically rolls back to the previous version if the build fails.
1. The Deploy Script
Create deploy.sh:
#!/bin/bash
# Automated deployment script with rollback on failure
set -e # Exit immediately if any command returns a non-zero status
APP_DIR="/var/www/myapp"
BACKUP_DIR="/var/backups/myapp"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_PATH="$BACKUP_DIR/backup_$TIMESTAMP"
echo "=== Starting deployment at $TIMESTAMP ==="
# 1. Create a backup of the current version
echo "Creating backup..."
mkdir -p "$BACKUP_DIR"
cp -r "$APP_DIR" "$BACKUP_PATH"
# 2. Pull latest code
echo "Pulling latest code from Git..."
cd "$APP_DIR"
git pull origin main
# 3. Install dependencies
echo "Installing dependencies..."
pnpm install --frozen-lockfile
# 4. Build project
echo "Building project..."
if pnpm run build; then
echo "Build succeeded!"
else
echo "ERROR: Build failed! Rolling back to previous version..."
rm -rf "$APP_DIR"
cp -r "$BACKUP_PATH" "$APP_DIR"
echo "Rollback complete. Previous version restored."
exit 1
fi
# 5. Restart service
echo "Restarting application service..."
pm2 restart myapp
echo "=== Deployment completed successfully ==="2. Running the Script
Make the script executable and run it on your server:
chmod +x deploy.sh
./deploy.shThe set -e directive at the top ensures the script halts at the first error, triggering the rollback logic.
Published on Last updated: