Search code examples
dockerjenkinsjenkins-pipelinejenkins-docker

Is it possible to get the docker container IP in Jenkins using the Docker plugin?


I am using the Jenkins Docker plugin in the pipeline to start a background mongodb container for testing, using:

stage('Start') {
  steps {
    script {
      container = docker.image('mongo:latest').run('-p 27017:27017 --name mongodb -d')
    }
  }
}

I need to get the container IP address to be able to connect to it. I found some examples online mentioning docker.inspect and docker.getIpAddress methods, but they are just throwing errors, and according to the source code for the Docker plugin I believe they don't even exist.

Is there a way to get the IP address from the container object?


Solution

  • Here is my solution (please test it on your own):

    stage('Start') {
      steps {
        script {
          def container = docker.image('mongo:latest').run('-p 27017:27017 --name mongodb -d')
    
          def ipAddress = null
    
          while (!ipAddress) {
    
            ipAddress = sh(
              returnStdout: true,
              script      : "docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' mongodb"
            )
    
            if (!ipAddress) {
              echo "Container IP address not yet available..."
              sh "sleep 2"
            }
    
          }
    
          echo "Got IP address = ${ipAddress}."
        }
      }
    }