Day 27: Jenkins Declarative Pipeline with Docker

Day 27: Jenkins Declarative Pipeline with Docker


Overview

Today, we dive deeper into integrating Docker with Jenkins Declarative Pipelines. By combining the flexibility of Docker and the power of Jenkins pipelines, DevOps engineers can automate builds and deployments seamlessly. Let’s break it down step-by-step.


Task 1: Docker-Integrated Declarative Pipeline

Here’s how to create a pipeline using sh commands for Docker build and run:

Pipeline Script

pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                sh 'docker build -t trainwithshubham/django-app:latest .'
            }
        }
        stage('Run') {
            steps {
                sh 'docker run -d --name django-app trainwithshubham/django-app:latest'
            }
        }
    }
}
        

Challenges

  1. Duplicate Container Names: Running the pipeline twice may fail due to an existing container.
  2. Solution: Stop and remove the container before starting a new one.

sh 'docker rm -f django-app || true'        

Task 2: Using Docker Groovy Syntax in Jenkins

To avoid shell script challenges, leverage Jenkins' Docker Groovy syntax for better integration.

Updated Pipeline

pipeline {
    agent {
        docker { image 'trainwithshubham/django-app:latest' }
    }

    stages {
        stage('Build') {
            steps {
                script {
                    docker.image('trainwithshubham/django-app:latest').build('.')
                }
            }
        }
        stage('Run') {
            steps {
                script {
                    docker.image('trainwithshubham/django-app:latest').run('-d --name django-app')
                }
            }
        }
    }
}
        

Benefits of Groovy Syntax

  • Automatically manages container lifecycle.
  • Cleaner and more structured code.

To view or add a comment, sign in

More articles by Akshay Ghalme

Insights from the community

Others also viewed

Explore topics