如何在声明性 Jenkins 管道中使用 Docker 的 --cache-from 构建标志?

How do I use Docker's --cache-from build flag in a declarative Jenkins pipeline?

我正在使用声明性 Jenkinsfile 来 运行 Docker 容器内的某些阶段。该过程运行正常,但构建时间通常很慢,因为我们的 CI 有很多从属设备,如果构建发生在没有层缓存的从属设备上,则整个构建需要一段时间。

我读到如果指定 --cache-from 标志,Docker 可以加快构建速度。如何指定 cache-from 标志和外部注册表的 URL 和凭据?

pipeline {

  agent { dockerfile true }
  environment {
    REPO = credentials('supersecret')
  }

  stages {
    stage('Prepare environment') {
      steps {

The pipeline syntax 授权附加参数

You can pass additional arguments to the docker build ... command with the additionalBuildArgs option, like agent

{ dockerfile { additionalBuildArgs '--build-arg foo=bar' } }

但是 cache-from 引用的图像可能位于具有自己的凭据的专用外部注册表中。
也许您可以在该注册表中设置一个只负责 docker login 的第一步。


另一种方法完全是为该特定构建重复使用相同的节点。
参见“Reusing node/workspace with per-stage Docker agents

pipeline {
  agent {
    label 'whatever'
  }
  stages {
    stage('build') {
      steps {
        sh "./build-artifact.sh"
      }
    }
    stage('test in docker') {
      agent {
        docker {
          image 'ubuntu:16.04'
          reuseNode true
        }
      }
      steps {
        sh "./run-tests-in-docker.sh"
      }
    }
  }
}

那么任何 docker build 都将从当前的本地图像缓存中受益。