Building Docker Images

Use the Docker Pipeline plugin to build container images as part of your pipeline.

Syntaxdocker.build("myapp:${env.BUILD_NUMBER}")

Containerizing your app is a common CI step. The Docker Pipeline plugin gives Jenkins a docker global variable for building and running images.

Building an image

docker.build('name:tag') runs docker build against your workspace and returns an image object you can push or run.

Requirements

  • Docker must be installed on the agent.
  • The Jenkins user needs permission to use the Docker daemon.

Tagging

A great practice is tagging images with the build number or Git commit so every image is traceable back to a build.

Example

Example · bash
pipeline {
    agent any
    stages {
        stage('Build Image') {
            steps {
                script {
                    def img = docker.build("myuser/myapp:${env.BUILD_NUMBER}")
                    echo "Built image: ${img.id}"
                }
            }
        }
    }
}

When to use it

  • A microservices team builds a Docker image for each service as part of the CI pipeline so every commit produces a deployable artifact.
  • A pipeline passes the Git commit SHA as a build argument so the image can be traced back to the exact source revision.
  • A multi-stage Dockerfile is built in Jenkins to produce a minimal production image without development dependencies.

More examples

Build Docker image in pipeline

Builds a Docker image tagged with the Jenkins build number and passes the Git commit as a build argument.

Example · groovy
stage('Docker Build') {
  steps {
    sh """
      docker build \\
        --build-arg GIT_COMMIT=${GIT_COMMIT} \\
        -t myapp:${BUILD_NUMBER} \\
        .
    """
  }
}

Build with Docker Pipeline plugin

Uses the Docker Pipeline plugin's docker.build() method to build and return an image object.

Example · groovy
pipeline {
  agent any
  stages {
    stage('Build Image') {
      steps {
        script {
          def img = docker.build("myapp:${env.BUILD_NUMBER}")
        }
      }
    }
  }
}

Multi-stage Dockerfile build

Builds only the production target of a multi-stage Dockerfile and uses the latest image as a layer cache.

Example · groovy
stage('Docker Build') {
  steps {
    sh """
      docker build \\
        --target production \\
        --cache-from registry/myapp:latest \\
        -t myapp:${BUILD_NUMBER} \\
        -t myapp:latest \\
        .
    """
  }
}

Discussion

  • Be the first to comment on this lesson.