pipeline { agent any tools { nodejs 'Node' // Make sure NodeJS installation in Jenkins Global Tool Config is named "Node" } environment { WEB_IP = '13.49.223.142' // EC2 web server IP SSH_CRED = 'deploy-ec2-key' // Jenkins SSH key credential ID NODE_OPTIONS = "--max_old_space_size=512" // Prevent Node from consuming all memory } stages { stage('Checkout') { steps { checkout scm } } stage('Install') { steps { sh ''' echo "📦 Installing dependencies..." npm ci ''' } } stage('Build') { steps { sh ''' echo "🏗️ Building project..." npm run build ''' } } stage('Package') { steps { sh ''' OUT_DIR="build" [ -d dist ] && OUT_DIR="dist" if [ ! -d "$OUT_DIR" ]; then echo "❌ ERROR: No build output found (build/ or dist/)" ls -la exit 1 fi echo "📦 Packaging build output..." tar -czf build.tar.gz -C "$OUT_DIR" . ''' archiveArtifacts artifacts: 'build.tar.gz' } } stage('Deploy') { steps { script { // Use sshagent for passwordless deployment sshagent([env.SSH_CRED]) { sh """ echo "🚀 Deploying to ${WEB_IP}..." # Copy build archive to web server scp -o StrictHostKeyChecking=no build.tar.gz deploy@${WEB_IP}:/tmp/build.tar.gz # Extract and reload nginx (passwordless sudo) ssh -o StrictHostKeyChecking=no deploy@${WEB_IP} ' sudo rm -rf /var/www/reactapp/* sudo mkdir -p /var/www/reactapp sudo tar -xzf /tmp/build.tar.gz -C /var/www/reactapp sudo systemctl reload nginx ' echo "✅ Deployment finished" """ } } } } } post { success { echo "✅ Pipeline completed successfully" } failure { echo "❌ Pipeline failed — check console log" } } }