Files
DevSecOps-Lab/Jenkinsfile
dev-1 e934074647
Some checks failed
DevSecOps-Multibranch/pipeline/head There was a failure building this commit
Update Jenkinsfile with optimized pipeline using shared repository and distinct image tags
2025-11-30 15:37:41 +05:30

87 lines
2.9 KiB
Groovy

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 {
script {
echo "Pushing images to DigitalOcean..."
sh "docker push ${REGISTRY_URL}/${REPO_NAME}:${BACKEND_TAG}"
sh "docker push ${REGISTRY_URL}/${REPO_NAME}:${FRONTEND_TAG}"
}
}
}
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}
"""
}
}
}
}
}