The Jenkinsfile Explained
July 14, 2025
The Jenkinsfile lives in the repo root and defines the pipeline as code.
Full pipeline
pipeline {
agent any
environment {
DOCKERHUB_USER = 'YOUR_DOCKERHUB_USERNAME'
INDEX_NO = 'YOUR_INDEX_NO'
DOCKERHUB_CREDS = credentials('dockerhub-creds')
}
stages {
stage('Checkout') { steps { checkout scm } }
stage('Build Backend Image') {
steps { sh 'docker build -f backend2/DOCKERFILE -t $DOCKERHUB_USER/${INDEX_NO}-backend:latest ./backend2' }
}
stage('Build Frontend Image') {
steps { sh 'docker build -f frontend2/DOCKERFILE -t $DOCKERHUB_USER/${INDEX_NO}-frontend:latest ./frontend2' }
}
stage('Docker Login') {
steps { sh 'echo $DOCKERHUB_CREDS_PSW | docker login -u $DOCKERHUB_CREDS_USR --password-stdin' }
}
stage('Push Images') {
steps {
sh 'docker push $DOCKERHUB_USER/${INDEX_NO}-backend:latest'
sh 'docker push $DOCKERHUB_USER/${INDEX_NO}-frontend:latest'
}
}
}
post {
always { sh 'docker logout || true' }
success { echo 'Images built and pushed to Docker Hub.' }
failure { echo 'Pipeline failed. Check stage logs.' }
}
}
Commit it to the repo:
git add Jenkinsfile
git commit -m "Add Jenkins pipeline"
git push origin main
What each part means (viva)
pipeline { }โ the declarative pipeline block.agent anyโ run on any available Jenkins agent/node.environment { }โ define variables;credentials('id')injects secrets safely.stages { }โ container for all stages.stage('X') { steps { } }โ one phase of the workflow.sh '...'โ run a shell command on the agent.checkout scmโ pull the repo configured in the job.--password-stdinโ pipe the password in without exposing it in logs.post { }โ runs after the stages:always,success,failure.
Gotchas
- The Dockerfile is named DOCKERFILE (caps), so builds must use
-f DOCKERFILE. - Never hardcode your password โ use credentials (see [[jenkins-docker-hub-credentials]]).
For the exam's 3-stage version, see [[jenkins-task3-pipeline]].