Jenkinsfile
Jenkinsfile with Multi-Stage Pipeline (Best Practices & Scenarios)
1. Basic Multi-Stage Jenkinsfile (Declarative Pipeline)
pipeline {
agent any
environment {
DOCKER_IMAGE = "myapp:latest"
}
stages {
stage('Checkout') {
steps {
git 'https://github.com/user/repo.git'
}
}
stage('Build') {
steps {
sh 'docker build -t $DOCKER_IMAGE .'
}
}
stage('Test') {
steps {
sh 'docker run --rm $DOCKER_IMAGE npm test'
}
}
stage('Push to Registry') {
when {
branch 'main'
}
steps {
withDockerRegistry([credentialsId: 'docker-hub-credentials', url: 'https://index.docker.io/v1/']) {
sh 'docker push $DOCKER_IMAGE'
}
}
}
stage('Deploy') {
when {
branch 'main'
}
steps {
sh './deploy.sh'
}
}
}
post {
success {
echo 'Pipeline executed successfully!'
}
failure {
echo 'Pipeline failed!'
}
}
}2. Breakdown of Key Sections
2.1 agent
agent2.2 environment (Global Variables)
environment (Global Variables)2.3 stages (Multi-Stage Structure)
stages (Multi-Stage Structure)Stage
Purpose
2.4 when Conditionals
when Conditionals2.5 post Actions
post Actions3. Optimized Jenkinsfile with Multi-Stage Docker Build
4. Multi-Stage Jenkinsfile with Parallel Execution
5. Best Practices for Jenkinsfiles
✅ Use Declarative Pipelines
✅ Keep Secrets in Jenkins Credentials
✅ Use when Conditions for Better Control
when Conditions for Better Control✅ Use Docker Caching
✅ Implement Parallel Execution
6. Scenario-Based Jenkinsfile Interview Questions
Q1: How do you run unit tests inside a container?
Q2: How do you ensure the deployment runs only on the main branch?
main branch?Q3: How do you store and use secrets securely in Jenkins?
7. Summary
Topic
Key Takeaways
Last updated