If else conditions for docker container in jenkins pipeline script

1.6k views Asked by At

I have created a pipeline in Jenkins whose steps are:

  1. git pull(retrieve the app from GitHub)
  2. build (maven package the app)
  3. building an image
  4. running an image

code for running the image is docker run -d --name **application_name** -p 8081:8081 **application_name**

I need an if-else condition to check if the image has been created or not. for eg.

if (image not created)
     create the image
else
     different step

I need this because every time I change something in code, Jenkins throws an error stating that the image is already running.

1

There are 1 answers

0
smelm On

The error might be related to this question.

You could just build the image anyway, since it wouldn't matter much if it was build again.

It you want to check if the image already exists you could use the docker images command and check if the image exists like described here.

It could look something like this:

script {
    def imageExists = sh(script: "docker images -q <image name>", returnStdout: true) == 0

    if(!imageExists){
        // build the image
    }
}