简体   繁体   中英

How to get a Docker image object in a Jenkins pipeline?

I have this code in a Jenkins pipeline, and it runs

def myImage = docker.build(...)
myImage.withRun(...) {img ->
    println img.id
}

IOW docker.build() returns some Jenkins pipeline Docker object that knows about the withRun() function.

But with this code I have to build the Docker image every time.

What if I want to pull the Docker image from a registry? How can I get the equivalent Jenkins pipeline Docker object that will have the withRun() function too? IOW, how can I make this (pseudo)code work? I say "pseudo" since there's no docker.pull() that I'm aware of?

docker.withRegistry(...)
  def myImage = docker.pull('someImage:latest')
  myImage.withRun() (...) {img ->
    println img.id
  }
}

Using Docker with Pipeline in the Jenkins documentation covers the typical cases. This is described under Running "sidecar" containers : you can call docker.image('someImage:latest') to get the image object, and its withRun method will pull the image if needed.

docker.withRegistry(...) {
  docker.image('someImage:latest').withRun() { container ->
    println container.id
  }
}

The Jenkins server itself has documentation on the globals; I can't easily find a canonical online reference, but try navigating to /pipeline-syntax/globals on your local Jenkins server and looking for the docker object. You can manually image.pull() if you need to (though note that .withRun() will pull the image on its own if it doesn't already exist locally).

Your examples all try to print out the ID of the image. That doesn't seem to be a property of the image object; image.id can exist but may not be informative

def image = docker.image('someImage:latest')
image.pull()
echo image.id // will print "someImage:latest"

If you really need to know this, you can run docker inspect to find it.

sh "docker inspect -f '{{ .Id }}' ${image.id}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM