Here in this post, I want to show a simple example of a pipeline, but how to work in different Stages with the same Docker Container, using files/products between the Stages and at the end, cleaning up Worspace.

The first point is the Jenkins Node, having assigned a Label, in this case, the Node that has Docker, I created the Docker label, so in the Pipeline having specified “docker label”, I know that it will always be executed on this Node.

In the script below, for the sake of curiosity, you can change “sleep 1”, to, for example, “sleep 600” (10 minutes) and you can also access the container in Docker, access Bash and check the entire structure and environment of the container created by Jenkins.

pipeline {
    agent {
        docker {
            image 'ubuntu_python:3.10.6'
            label 'docker'
            args '-u root'
        }
    }
    options { timestamps () 
              skipDefaultCheckout(true)
            }
    stages {
        stage('Build') {
            agent {
                label 'docker'
            }      
            steps {
                sh 'date >> data.txt'
                sh 'ls -lah'
            }
        }
        stage('Finish') {
            agent {
            label 'docker'
            }       
            steps {
                sh 'ls -lah'
                sh 'cat data.txt'
                sh 'sleep 1'
            }
        }
        stage('Cleanup') {
            agent {
                label 'docker'
            }               
            steps {            
                cleanWs deleteDirs: true, disableDeferredWipeout: true
            }
        }        
    }
}

Docker Container example.

docker container ls
CONTAINER ID   IMAGE                  COMMAND                  CREATED              STATUS              PORTS                                                                                      NAMES
0bcfe65abf2a   ubuntu_python:3.10.6   "cat"                    About a minute ago   Up About a minute                                                                                              great_payne

docker exec -it -u root --privileged great_payne /bin/bash
root@0bcfe65abf2a:/var/jenkins_home/workspace/test_pipeline# ll
total 8
drwx------ 1 502 dialout 192 May  7 21:33 ./
drwx------ 1 502 dialout 608 May  6 21:48 ../
drwx------ 1 502 dialout 320 Apr 22 21:58 .git/
-rw-r--r-- 1 502 dialout  85 May  7 21:38 data.txt
drwx------ 1 502 dialout  64 Apr 22 21:49 test_pipeline/

See the execution result:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.