pipeline { agent { label 'jenkins-agent' } environment { REGISTRY_URL = 'registry.digitalocean.com/kongseng' // FIX: Use ONE shared repository name REPO_NAME = 'devsecops-lab' // Create distinct tags for backend and frontend // Result: registry.../devsecops-lab:backend-Dev-1 BACKEND_TAG = "backend-${env.BRANCH_NAME}-${env.BUILD_NUMBER}" FRONTEND_TAG = "frontend-${env.BRANCH_NAME}-${env.BUILD_NUMBER}" } stages { stage('Checkout') { steps { checkout scm } } stage('Install Dependencies') { steps { // Check if folders exist to avoid errors sh 'ls -la' dir('backend') { sh 'npm install' } dir('frontend') { sh 'npm install' } } } stage('Build Docker Images') { steps { script { echo "Building Images..." // Build both images using the SAME Repo URL but DIFFERENT Tags sh "docker build -t ${REGISTRY_URL}/${REPO_NAME}:${BACKEND_TAG} ./backend" sh "docker build -t ${REGISTRY_URL}/${REPO_NAME}:${FRONTEND_TAG} ./frontend" } } } stage('Push to Registry') { steps { // Securely inject the token into the script withCredentials([string(credentialsId: 'do-registry-token', variable: 'DO_TOKEN')]) { script { echo "Logging into DigitalOcean Registry..." // Explicit Login: Uses the token as both user and password (DO Standard) sh 'echo $DO_TOKEN | docker login registry.digitalocean.com -u $DO_TOKEN --password-stdin' echo "Pushing images..." sh "docker push ${REGISTRY_URL}/${REPO_NAME}:${BACKEND_TAG}" sh "docker push ${REGISTRY_URL}/${REPO_NAME}:${FRONTEND_TAG}" // Cleanup: Logout to keep the agent secure sh 'docker logout registry.digitalocean.com' } } } } stage('Deploy') { steps { script { def appPort = "3000" // Unique container name for this branch def containerName = "app-${env.BRANCH_NAME}" if (env.BRANCH_NAME == 'Dev') { appPort = "3001" } else if (env.BRANCH_NAME == 'Release') { appPort = "3002" } else if (env.BRANCH_NAME == 'main') { appPort = "3003" } echo "Deploying Backend to Port ${appPort}..." // Clean up old container try { sh "docker stop ${containerName} || true" sh "docker rm ${containerName} || true" } catch (Exception e) { echo "No container to stop" } // Run the specific BACKEND tag sh """ docker run -d \ --name ${containerName} \ --restart always \ -p ${appPort}:3000 \ ${REGISTRY_URL}/${REPO_NAME}:${BACKEND_TAG} """ } } } } }