BASH
Automate Web App Deployment with Git and NPM
A bash script to automate web application deployment, including pulling the latest code from Git, installing Node.js dependencies, and restarting a PM2 or systemd service.
#!/bin/bash
# --- Configuration ---
APP_DIR="/var/www/mywebapp"
BRANCH="main"
PM2_APP_NAME="mywebapp-api" # Or systemd service name, e.g., "mywebapp.service"
# --- Deployment Steps ---
echo "Starting deployment for ${PM2_APP_NAME}..."
# Navigate to application directory
cd "${APP_DIR}" || { echo "Error: Application directory not found!"; exit 1; }
# Pull latest code from Git
echo "Pulling latest code from Git branch '${BRANCH}'..."
git reset --hard HEAD
git clean -df
git pull origin "${BRANCH}" || { echo "Error: Git pull failed!"; exit 1; }
# Install Node.js dependencies
if [ -f "package.json" ]; then
echo "Installing Node.js dependencies..."
npm install --production || { echo "Error: npm install failed!"; exit 1; }
else
echo "No package.json found, skipping npm install."
fi
# Restart application service (using PM2 or systemd)
if command -v pm2 &> /dev/null; then
echo "Restarting application with PM2: ${PM2_APP_NAME}..."
pm2 reload "${PM2_APP_NAME}" || { echo "Error: PM2 reload failed!"; exit 1; }
elif command -v systemctl &> /dev/null; then
echo "Restarting application with systemctl: ${PM2_APP_NAME}..."
sudo systemctl restart "${PM2_APP_NAME}" || { echo "Error: systemctl restart failed!"; exit 1; }
else
echo "Neither PM2 nor systemctl found. Manual restart might be needed."
fi
echo "Deployment completed successfully for ${PM2_APP_NAME}."
How it works: This script automates common web application deployment steps. It navigates to the app directory, pulls the latest code from a specified Git branch, installs Node.js dependencies if a `package.json` exists, and then restarts the application using either PM2 or systemd, depending on what's available. Error handling ensures the script exits if a step fails.