How to build multiple containers in Jenkins file?

8/30/2019

I have 3 different Docker images. I need to build these images from Jenkins file. I have Wildfly, Postgres, Virtuoso Docker images with individual Docker file. As of now, I am using the below command to build these images:

'sh docker build docker docker-compose.yml'

My question is how build these 3 images from Jenkins file?

-- Pavan Patil
devops
docker
docker-container
jenkins-pipeline
kubernetes

2 Answers

8/30/2019

Working with pipeline better to use Docker plugin as mentioned by @Linpy.

I assume that you already have Dockerfile for each image in the current workspace.

current_workspace/dockerdb
current_workspace/dockerapp
current_workspace/imagebla

Update the name of the folder as you are using local.

    pipeline {
        agent any
        stages {
            stage('Build image') {
                steps {
                    echo 'Starting to build docker image DB'
                    script {
                        def DB = docker.build("my-image:${env.BUILD_ID}","-f ${env.WORKSPACE}/db/Dockerfile .")
                        def nodejs = docker.build("my-image:${env.BUILD_ID}","-f ${env.WORKSPACE}/app/Dockerfile .") 
                        def php = docker.build("my-image:${env.BUILD_ID}","-f ${env.WORKSPACE}/php/Dockerfile .") 
                    }
                }
            }
        }
    }
-- Adiii
Source: StackOverflow

8/30/2019

Referring to your note below your answer, you can try this simple approach without using plugins:

stage('Building Docker Image') {
   # Creating and running the first one
   dir ('/path/to/your/directory1') {
      sh 'docker build --<docker-options> -t $DOCKER_IMAGE_NAME_1 .'
      sh 'docker run $DOCKER_IMAGE_NAME_1'
   }

   # Creating and running the first one
   dir ('/path/to/your/directory2') {
      sh 'docker build --<docker-options> -t $DOCKER_IMAGE_NAME_2 .'
      sh 'docker run $DOCKER_IMAGE_NAME_2'
   }
}

or the same if you are using docker-compose

...
sh 'docker-compose build'
sh 'docker-compose up'
...

Note for your path to the Dockerfile: You are working in jenkins workspace!


There is also a plugin for this as @LinPy mentioned. Have a look at: the Jenkins-Documentation under Using multiple containers.

-- agentsmith
Source: StackOverflow