BASH

Automate Git Pull, Dependency Install, and Service Restart for Web Deployments

A Bash script to automate web application deployments. It pulls the latest code, installs dependencies, and restarts your service efficiently.

#!/bin/bash
# --- Configuration ---
APP_DIR="/var/www/my-web-app"
SERVICE_NAME="my-web-app.service" # Or PM2 process name, or simple restart command
LOG_FILE="/var/log/my-web-app-deploy.log"

# --- Logging Function ---
log_message() {
  echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# --- Deployment Steps ---
log_message "Starting deployment for $APP_DIR"

cd "$APP_DIR" || { log_message "Error: Could not change to application directory."; exit 1; }

log_message "Pulling latest code from Git..."
git pull origin main || { log_message "Error: Git pull failed."; exit 1; }

log_message "Installing/updating dependencies..."
# Example for Node.js:
npm install --production || { log_message "Error: npm install failed."; exit 1; }
# Example for PHP (Composer):
# composer install --no-dev --optimize-autoloader || { log_message "Error: Composer install failed."; exit 1; }

log_message "Restarting application service..."
# Example for systemd:
sudo systemctl restart "$SERVICE_NAME" || { log_message "Error: Service restart failed."; exit 1; }
# Example for PM2:
# pm2 restart "$SERVICE_NAME" || { log_message "Error: PM2 restart failed."; exit 1; }

log_message "Deployment completed successfully."
How it works: This script automates a common web deployment workflow. It navigates to the application directory, pulls the latest code from Git, installs project dependencies (e.g., `npm install` for Node.js or `composer install` for PHP), and finally restarts the application service (e.g., using `systemctl` or `pm2`). Error handling and logging are included to ensure robustness and traceability.

Need help integrating this into your project?

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

Hire DigitalCodeLabs