如何在Jenkins声明性管道中从docker hub推送和拉出

时间:2017-03-28 08:56:03

标签: docker jenkins jenkins-pipeline

我正在使用标准的“sh”命令从奴隶上的jenkinsfile管道中成功构建docker镜像。

我希望能够尝试从docker / hub中提取图像,如果它失败(因为它尚未保存),请构建它并将其推送到docker hub。

显然我需要存储docker hub的凭据并将它们提供给docker login命令。

我的问题是我很困惑。有docker管道插件,但我认为它们是用于在docker容器中运行jenkins步骤 - 而不是我想要做的事情。此外,许多示例似乎是脚本化管道而不是声明性。

在简单的“步骤”术语中,我认为我想做一些像

这样的事情
agent {
    label 'pi'
}
steps {
  sh 'docker login -u my-account -p xxxx'
  sh 'docker pull my-account/image:version || (docker build -f dockerfile -t my-account/image:version && docker push my-account/image:version)'
....
}

但我也怀疑我可能需要做像

这样的事情
steps {
  script {
    withDockerRegistry([credentialsId: 'something', url: 'docker.io/my-account']) {
      sh 'docker pull my-account/image:version || (docker build -f dockerfile -t my-account/image:version && docker push my-account/image:version)'
    ....
  }
}

但我不想犯任何错误,并且除了这一点之外,还要搞一个目前工作正常的管道。

我是沿着正确的路线吗?

2 个答案:

答案 0 :(得分:6)

如果你有Docker pipeline plugin,你可以创建和推送这样的图像。

dir(config.buildFolder){
                newImage = docker.build(${imageTag})
                docker.withRegistry("https://${registryAddress}", '${credentialsId}'){
                     newImage.push("${variables.version}")

            }

您可以在容器中拉取并执行一些代码,如下所示:

testbed = docker.image('${imageName}')
testbed.inside("-u root:root"){
                echo 'executing build inside container'
                sh 'dotnet restore'
            }

这将自动将创建容器的文件夹作为容器的根目录挂载,以便您可以使用该数据(如构建应用程序)

答案 1 :(得分:0)

我也在处理同样的问题。我希望从我的Dockerhub仓库中提取Docker镜像并使用它们执行一些测试。我已按照此处显示的步骤设法让我的管道工作。

https://spring.io/blog/2014/10/15/whats-new-in-spring-data-evans#user-content-statically-limiting-results