← Back to all snippets
BASH

Automated Web App Deployment with Git Pull

Automate web application deployments using a simple Bash script that pulls the latest code from Git, installs dependencies, and restarts services.

#!/bin/bash

# --- Configuration ---
REPO_DIR="/var/www/mywebapp"
SERVICE_NAME="mywebapp-service.service"

# --- Deployment Steps ---

echo "Starting deployment for $(basename $REPO_DIR)..."

# Navigate to repository directory
cd $REPO_DIR || { echo "Error: Directory $REPO_DIR not found."; exit 1; }

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

# Install Node.js dependencies (example for Node.js apps)
if [ -f "package.json" ]; then
  echo "Installing Node.js dependencies..."
  npm install || { echo "Error: npm install failed."; exit 1; }
fi

# Run build process (example for frontend builds)
if [ -f "webpack.config.js" ] || [ -f "vite.config.js" ]; then
  echo "Running build process..."
  npm run build || { echo "Error: Build process failed."; exit 1; }
fi

# Restart web service (e.g., Systemd service)
echo "Restarting $SERVICE_NAME..."
sudo systemctl restart $SERVICE_NAME || { echo "Error: Failed to restart $SERVICE_NAME. Check service status."; exit 1; }

echo "Deployment complete!"
How it works: This Bash script automates the common steps for deploying a web application. It navigates to the project directory, pulls the latest code from the `main` branch, conditionally runs `npm install` and a build process if `package.json` or build configuration files are present, and finally restarts a specified system service to apply the changes. This streamlines the deployment workflow.

Need help integrating this into your project?

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

Hire DigitalCodeLabs