Jenkins / Docker:如何在构建之前强制拉基础图像

时间:2017-07-12 12:06:57

标签: docker jenkins jenkins-pipeline

Docker允许将--pull标记传递给docker build,例如docker build --pull -t myimage .。如何在我的Jenkinsfile中使用管道脚本强制提取基本图像?这样我想确保构建始终使用最新的容器映像,尽管本地可用的版本。

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")
        }
    }
}

3 个答案:

答案 0 :(得分:4)

最直接的答案是使用docker.build

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

如果您不提供它,那么它只是默认为.,所以如果您传入任何内容,您还必须自己包含上下文。

您可以在“管道语法 - 全局变量参考”中找到它。只需将/pipeline-syntax/globals添加到任何Jenkins网址的末尾(即http://localhost:8080/job/myjob/pipeline-syntax/globals

答案 1 :(得分:2)

additionalBuildArgs完成这项工作。

示例:

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"
                    }
                }
            }
        }

        […]
    }

}

答案 2 :(得分:0)

脚本开头的

docker rmi <image>docker build --pull之前。执行docker build --pull时,图像不会在本地存在,因此每次都会重新下载。

相关问题