BASH
Automate Git Pull and Application Restart for Deployments
Streamline web application deployments by automatically pulling the latest code from a Git repository and restarting a systemd service, ensuring quick updates.
#!/bin/bash
# Script to pull latest code and restart a systemd service for web application deployments
# Configuration
APP_DIR="/var/www/mywebapp" # Root directory of your web application
GIT_BRANCH="main" # The Git branch to pull from (e.g., main, master, production)
SERVICE_NAME="mywebapp.service" # The name of your systemd service (e.g., nginx, apache2, nodeapp.service)
echo "========================================"
echo "Starting deployment script for $APP_DIR"
echo "========================================"
# Navigate to the application directory
cd "$APP_DIR" || {
echo "Error: Application directory '$APP_DIR' not found or not accessible."
echo "Please check the APP_DIR variable and directory permissions."
exit 1
}
echo "Current working directory: $(pwd)"
# Pull latest changes from Git
echo "Pulling latest changes from Git branch '$GIT_BRANCH'..."
# 'git reset --hard' ensures a clean state before pulling, discarding local changes
# 'git pull origin $GIT_BRANCH' fetches and merges the latest changes
git reset --hard origin/"$GIT_BRANCH" && git pull origin "$GIT_BRANCH" || {
echo "Error: Git pull failed. Please check repository access and branch name."
exit 1
}
echo "Git pull completed successfully."
# Restart the application service
echo "Restarting service '$SERVICE_NAME'..."
sudo systemctl restart "$SERVICE_NAME" || {
echo "Error: Failed to restart service '$SERVICE_NAME'."
echo "Please check the service name and 'sudo' permissions."
exit 1
}
echo "Service '$SERVICE_NAME' restarted successfully."
echo "========================================"
echo "Deployment script finished successfully!"
echo "========================================"
How it works: This script automates the deployment process for a web application. It navigates to the specified application directory, performs a `git pull` to fetch the latest code from a designated branch, and then restarts a systemd service associated with the application. This ensures that the newly pulled code is active. It includes basic error handling to exit if directories or commands fail, making it robust for CI/CD pipelines or manual deployment tasks.