BASH

Automating Web Application Deployment via Git Pull and Service Restart

Streamline your web application deployment process with a Bash script that pulls the latest code from Git, installs dependencies, and restarts critical services like Nginx or Apache.

#!/bin/bash

# Configuration
APP_DIR="/var/www/my_webapp"
WEB_SERVER_SERVICE="nginx" # Or 'apache2'

# --- Deployment Steps ---

echo "Starting deployment for ${APP_DIR}..."

# 1. Navigate to the application directory
cd "${APP_DIR}" || {
  echo "Error: Cannot change directory to ${APP_DIR}. Aborting."
  exit 1
}

# 2. Pull the latest code from Git
echo "Pulling latest code from Git..."
git pull origin main || {
  echo "Error: Git pull failed. Aborting."
  exit 1
}

# 3. (Optional) Install/Update PHP Composer dependencies
if [ -f "composer.json" ]; then
  echo "Installing Composer dependencies..."
  composer install --no-dev --optimize-autoloader || {
    echo "Error: Composer install failed. Aborting."
    exit 1
  }
fi

# 4. (Optional) Install/Update Node.js dependencies (for frontend assets)
if [ -f "package.json" ]; then
  echo "Installing Node.js dependencies and building assets..."
  npm install --omit=dev && npm run build || {
    echo "Error: Node.js dependencies or build failed. Aborting."
    exit 1
  }
fi

# 5. (Optional) Run database migrations
if [ -f "artisan" ]; then # For Laravel applications
  echo "Running database migrations..."
  php artisan migrate --force || {
    echo "Error: Database migrations failed. Aborting."
    exit 1
  }
fi

# 6. Clear caches (example for Laravel)
if [ -f "artisan" ]; then
  echo "Clearing application caches..."
  php artisan optimize:clear
fi

# 7. Restart web server service
echo "Restarting ${WEB_SERVER_SERVICE} service..."
sudo systemctl restart "${WEB_SERVER_SERVICE}" || {
  echo "Error: Failed to restart ${WEB_SERVER_SERVICE}. Aborting."
  exit 1
}

echo "Deployment successful!"
How it works: This Bash script automates the deployment of a web application. It first navigates to the application directory, then pulls the latest code from a Git repository. It includes optional steps for installing PHP Composer dependencies, Node.js dependencies, building frontend assets, running database migrations (e.g., for Laravel), and clearing application caches. Finally, it restarts the specified web server service (Nginx or Apache) to ensure the changes are live. Error checks are included at each critical step to halt the script if a command fails.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs