my-react-app/Jenkinsfile

84 lines
1.9 KiB
Groovy

pipeline {
agent any
tools {
nodejs 'Node' // Jenkins -> Global Tool Config -> NodeJS must be named "Node"
}
environment {
WEB_IP = '13.49.223.142' // update if EC2 IP changes
SSH_CRED = 'deploy-ec2-key' // Jenkins credential ID for your EC2 SSH key
NODE_OPTIONS = "--max_old_space_size=512" // prevent Node from eating all memory
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Install') {
steps {
sh '''
echo "📦 Installing dependencies..."
npm install
'''
}
}
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 {
sshagent(credentials: [env.SSH_CRED]) {
sh '''
echo "🚀 Deploying to ${WEB_IP} ..."
scp -o StrictHostKeyChecking=no build.tar.gz deploy@${WEB_IP}:/tmp/build.tar.gz
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" }
}
}