pipeline { // 1. Run on your specific agent agent { label 'jenkins-agent' } environment { REGISTRY_URL = 'registry.digitalocean.com/kongseng' // 2. Dynamic Naming: Image tag includes Branch Name to prevent conflicts // Example: registry.../backend:Dev-42 or registry.../backend:main-42 BACKEND_IMAGE = "${REGISTRY_URL}/devsecops-backend:${env.BRANCH_NAME}-${env.BUILD_NUMBER}" FRONTEND_IMAGE = "${REGISTRY_URL}/devsecops-frontend:${env.BRANCH_NAME}-${env.BUILD_NUMBER}" } stages { stage('Checkout') { steps { checkout scm } } stage('Install Dependencies') { steps { echo "Installing dependencies for ${env.BRANCH_NAME} branch..." dir('backend') { sh 'npm install' } dir('frontend') { sh 'npm install' } } } stage('Build Docker Images') { steps { script { echo "Building Images for branch: ${env.BRANCH_NAME}..." sh "docker build -t ${BACKEND_IMAGE} ./backend" sh "docker build -t ${FRONTEND_IMAGE} ./frontend" } } } stage('Push to Registry') { steps { script { echo "Pushing images to DigitalOcean..." sh "docker push ${BACKEND_IMAGE}" sh "docker push ${FRONTEND_IMAGE}" } } } // --- DYNAMIC DEPLOYMENT --- stage('Deploy') { steps { script { // Define ports and names based on the branch def appPort = "3000" // Fallback def containerName = "backend-app" if (env.BRANCH_NAME == 'Dev') { appPort = "3001" containerName = "backend-dev" echo "Deploying to DEV Environment (Port 3001)" } else if (env.BRANCH_NAME == 'Release') { appPort = "3002" containerName = "backend-release" echo "Deploying to STAGING Environment (Port 3002)" } else if (env.BRANCH_NAME == 'main') { appPort = "3003" containerName = "backend-prod" echo "Deploying to PRODUCTION Environment (Port 3003)" } else { // Logic for any future feature branches appPort = "3004" containerName = "backend-feature-${env.BRANCH_NAME}" echo "Deploying Feature Branch" } // 1. Clean up old container try { sh "docker stop ${containerName} || true" sh "docker rm ${containerName} || true" } catch (Exception e) { echo "No container to stop" } // 2. Run new container on the assigned port sh """ docker run -d \ --name ${containerName} \ --restart always \ -p ${appPort}:3000 \ ${BACKEND_IMAGE} """ } } } } }