building a docker image only if it does not exists in Jenkins

Viewed 8452

I'm putting together a build pipeline in Jenkins using Docker containers, I want to build an image, but only if that image does not exist on the same server that Jenkins is running on. I'm after the simplest and most elegant way of doing this, but I'm struggling to come up with anything.

2 Answers

As stated in the answer for this question, you can use the following to check if the image exists.

if [[ "$(docker images -q myimage:mytag 2> /dev/null)" == "" ]]; then
  # do something
fi

You can take the output from:

docker image ls

Then grep for the image name you intend to build.

However, if you "build" an image in Jenkins, that will create a "new" image - even if the pre-existing image should be the same - how do you know?

Docker images are templates - it sounds like you're rebuilding images on different hosts? If so, consider using a central (private) registry and pulling from the various hosts that may require that image.

Related