Day 27: Jenkins Declarative Pipeline with Docker

Day 27: Jenkins Declarative Pipeline with Docker

90DaysOfDevOps

·

2 min read

Day 26 was all about a Declarative pipeline, now its time to level up things, let's integrate Docker and your Jenkins declarative pipeline

Use your Docker Build and Run Knowledge

docker build - you can use sh 'docker build . -t <tag>' in your pipeline stage block to run the docker build command. (Make sure you have docker installed with correct permissions.

docker run: you can use sh 'docker run -d <image>' in your pipeline stage block to build the container.

How will the stages look

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

Task-01

  • Create a docker-integrated Jenkins declarative pipeline

  • Use the above-given syntax using sh inside the stage block

Steps -

Create a new pipeline with the below code in pipeline -

pipeline {
    agent any
    stages{
        stage('Code'){
            steps{
                git url:'https://github.com/Moizasif/node-todo-cicd.git', branch:'master'
            }
        }
        stage('Build'){
            steps {
                sh 'docker build -t node-todo-app .'
            }
        }
        stage('Deploy'){
            steps{
                sh 'docker run -d -p 8000:8000 node-todo-app'
            }
        }
    }
}

You'll see the build completed successfully executing all stages of the pipeline.

  • You will face errors in case of running a job twice, as the docker container will be already created, so for that do task 2

Task-02

  • Create a docker-integrated Jenkins declarative pipeline using the docker groovy syntax inside the stage block.

  • You won't face errors, you can Follow this documentation

  • Complete your previous projects using this Declarative pipeline approach

Steps -

  1. To include docker in the stage block, the docker pipeline and docker plugin need to be installed.

  2. We should have our image uploaded to dockerhub.

We can install them from Manage Jenkins>manage plugins

Create a pipeline with below code -

This pipeline script sets up two stages: "Build" and "Run." In the "Build" stage, a Docker agent is used to create a Docker image using the provided image name. The "reuseNode" option is enabled, meaning the same Jenkins agent will be used for both the "Build" and "Run" stages.

Thank you for reading this article!