Jenkins Declarative Pipeline with Docker

Dhwarika JhaDhwarika Jha
2 min read

Table of contents

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.

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

  1. Create a docker-integrated Jenkins declarative pipeline

    In Jenkins, Click on “New Item”, create a new pipeline job, and select "Pipeline" as the project type.

  2. Use the above-given syntax using sh inside the stage block

    In the configuration, In the pipeline script section, define your stages, steps, and parameters.

     pipeline{
         agent any
    
         stages{
             stage("Code Clone"){
                 steps{
                     git branch : 'develop', url:'https://github.com/dwarika9167/django-todo-cicd.git'
                 }
             }
         stage("Code Build"){
                 steps{
                     sh 'docker build . -t django-node-todo:latest ' 
                 }
             }
         stage("Code Testing"){
                 steps{
                   echo 'testing'  
                 }
             }
         stage("code Deploy"){
                 steps {
                     sh 'docker run -d -p 8000:8000 django-node-todo:latest'
                 }
             }
         }
     }
    
  3. Save and run the pipeline. You should see the pipeline execute each stage and run your application inside a Docker container.

  4. Console Output:

  5. 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.

  1. We can solve the error with the help of docker-compose, by modifying the script using the docker-compose down and up commands

     stage("code Deploy"){
                 steps {
                     sh 'docker-compose down'
                     sh 'docker-compose up'
                 }
             }
    

  2. Click on Save and then click on Build Now.

  3. Because of insufficient memory, it is stuck in the deploy state but you can see in below screenshot our container is running also our Application running Properly.

0
Subscribe to my newsletter

Read articles from Dhwarika Jha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dhwarika Jha
Dhwarika Jha