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.
Asked
Active
Viewed 9,824 times
3
-
are you using any jenkins docker plugins or direct shell commands? – yamenk Sep 26 '17 at 08:57
-
I'm using shell commands, but I'm happy to use the plugin if this provides the most elegant way of doing things. – ChrisAdkin Sep 26 '17 at 09:02
-
Is there a reason why you don't want to build the image if it already exists? Unless the content of your image changes each time you build it, the Docker build cache will mean a re-build of an already existing image will be nearly instantaneous. – Rob Lockwood-Blake Sep 26 '17 at 09:25
2 Answers
9
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
-
Thanks, my apologies, I should have stated this in the question, I require a method that will work on windows. – ChrisAdkin Sep 26 '17 at 12:50
-
Having said that, I can probably take what you have given me and adapt it to use PowerShell. – ChrisAdkin Sep 26 '17 at 12:51
-
@ChrisAdkin yes basically the -q option for `docker images` should work the same on windows. – yamenk Sep 26 '17 at 12:52
0
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.

Michael
- 7,348
- 10
- 49
- 86