Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins/Docker: How to force pull base image before build

Docker allows passing the --pull flag to docker build, e.g. docker build --pull -t myimage .. How can I enforce pulling the base image with a pipeline script in my Jenkinsfile? This way I want to ensure that the build always uses the latest container image despite of the version available locally.

node('docker') {
    def app

    stage('Checkout') {
        checkout scm
    }

    stage('Build image') {
        docker.withRegistry('https://myregistry.company.com', 'dcr-jenkins') {
            app = docker.build "myimage"
        }
    }

    stage('Publish image') {
        docker.withRegistry('https://myregistry.company.com', 'dcr-jenkins') {
            app.push("latest")
        }
    }
}
like image 624
Stephan Avatar asked Jul 12 '17 12:07

Stephan


2 Answers

The most straight-forward answer is to use the second argument to docker.build

stage('Build image') {
    docker.withRegistry('https://myregistry.company.com', 'dcr-jenkins') {
        app = docker.build("myimage", "--pull .")
    }
}

If you don't supply it then it just defaults to ., so if you pass in anything you must also include the context yourself.

You can find this in the "Pipeline Syntax - Global Variable Reference". Just add /pipeline-syntax/globals to the end of any Jenkins URL (i.e. http://localhost:8080/job/myjob/pipeline-syntax/globals)

like image 174
Evan Borgstrom Avatar answered Nov 11 '22 02:11

Evan Borgstrom


additionalBuildArgs does the job.

Example:

pipeline {
    agent {
        label "docker"
    }

    stages {
        […]

        stage('Build image') {
            agent {
                dockerfile {
                    reuseNode true
                    registryUrl "https://registry.comapny.com"
                    registryCredentialsId "dcr-jenkins"
                    additionalBuildArgs "--pull --build-arg APP_VERSION=${params.APP_VERSION}"
                    dir "installation/app"
                }
            }

            steps {
                script {
                    docker {
                        app = docker.build "company/app"
                    }
                }
            }
        }

        […]
    }

}
like image 33
Stephan Avatar answered Nov 11 '22 02:11

Stephan