pipeline { agent any environment { SSH_CREDENTIALS = 'tech4biz-web' GIT_CREDENTIALS = 'gitea-cred' REPO_URL = 'https://git.tech4biz.wiki/Tech4Biz-Services/Tech4Biz-Website-Containerized.git' BRANCH = 'main' REMOTE_SERVER = 'ubuntu@160.187.167.14' REMOTE_DIR = '/home/ubuntu/tech4biz-website' IMAGE_NAME = 'tech4biz-web' CONTAINER_NAME = 'tech4biz-web' APP_PORT = '5173' NOTIFY_EMAIL = 'devops@tech4biz.wiki' } options { disableConcurrentBuilds() } stages { stage('Add Remote Host Key') { steps { echo "๐Ÿ”‘ Adding remote host key to known_hosts..." sshagent(credentials: [SSH_CREDENTIALS]) { sh ''' mkdir -p ~/.ssh ssh-keyscan -H 160.187.167.14 >> ~/.ssh/known_hosts ''' } } } stage('Checkout Code from Gitea') { steps { echo "๐Ÿ“ฆ Cloning repository from Gitea..." git credentialsId: "${GIT_CREDENTIALS}", url: "${REPO_URL}", branch: "${BRANCH}" } } stage('Deploy and Build Docker Image') { steps { echo "๐Ÿšข Sending code to remote and building Docker image..." sshagent(credentials: [SSH_CREDENTIALS]) { sh ''' ssh ${REMOTE_SERVER} "sudo mkdir -p ${REMOTE_DIR} && sudo chown -R ubuntu:ubuntu ${REMOTE_DIR}" # Exclude .git directory to prevent file not found errors rsync -avz --delete --exclude='.git' ./ ${REMOTE_SERVER}:${REMOTE_DIR}/ ssh ${REMOTE_SERVER} "cd ${REMOTE_DIR} && docker build -t ${IMAGE_NAME} ." ''' } } } stage('Run Docker Container') { steps { echo "๐Ÿณ Running Docker container on remote server..." sshagent(credentials: [SSH_CREDENTIALS]) { sh ''' ssh ${REMOTE_SERVER} "docker rm -f ${CONTAINER_NAME} || true && \ docker run -d -p ${APP_PORT}:${APP_PORT} --name ${CONTAINER_NAME} ${IMAGE_NAME} && \ docker update --restart=always ${CONTAINER_NAME}" ''' } } } stage('Reload Nginx') { steps { echo "๐ŸŒ Reloading Nginx on remote server..." sshagent(credentials: [SSH_CREDENTIALS]) { sh ''' ssh ${REMOTE_SERVER} "sudo nginx -t && sudo systemctl reload nginx" ''' } } } } post { success { echo "โœ… Deployment succeeded. Sending notification email..." mail to: "${NOTIFY_EMAIL}", subject: "โœ… Jenkins Job Success: ${env.JOB_NAME} #${env.BUILD_NUMBER}", body: "Good news!\n\nThe Jenkins job ${env.JOB_NAME} #${env.BUILD_NUMBER} completed successfully.\n\n- Jenkins" } failure { echo "โŒ Deployment failed. Sending notification email..." mail to: "${NOTIFY_EMAIL}", subject: "โŒ Jenkins Job Failed: ${env.JOB_NAME} #${env.BUILD_NUMBER}", body: "The Jenkins job ${env.JOB_NAME} #${env.BUILD_NUMBER} has failed.\nPlease check the Jenkins console output for more details.\n\n- Jenkins" } always { echo "๐Ÿงน Cleaning workspace..." cleanWs() } } }