0

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?

vgru
  • 49,838
  • 16
  • 120
  • 201
  • Is the build running inside a container, or directly on a node? If the main build isn't in a container then you should be able to connect to `localhost` and the first `-p` port number; you shouldn't ever need to look up the Docker-internal IP address. – David Maze May 03 '23 at 10:00
  • The agent where the pipeline is running is a docker agent, but I also have this other container with mongodb. So the test script is running outside this mongodb container, and it requires the url to connect to mongo. – vgru May 03 '23 at 10:04

1 Answers1

1

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}."
    }
  }
}
Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74
  • 1
    I was hoping there was a builtin way in the plugin, but this is similar to what I ended up doing. Thanks! – vgru May 03 '23 at 10:01