jenkinsgroovyjenkins-pipeline

Find unused port in Jenkins Pipeline Library


I am currently working on improving my Jenkins Pipeline, which starts a docker container with an exposed port. But due to the fact, that the Jenkins instance is heavily used by many people and their projects, I have run into the problem, that the exposed port mapping is already in use.

My idea is to determine an unused port on the host machine, to circumvent this problem. In order to do this, I want to expand our Jenkins shared the library with a simple method to check and return the first unused port from the host system.

Has anyone an idea how to achieve this?

My current solution would be to utilize a shell function which somehow uses the netstat tool.

File: getRandomFreePort.groovy

def call() {
sh '''
    #!/bin/bash
    while
    [[!-z $CHECK]]; do
    PORT = $(((RANDOM % 60000) + 1025))
    CHECK = $(sudo netstat - ap | grep $PORT)
    done

    echo $PORT
'''
}

Solution

  • Using ServerSocket you can get a unused port with this command:

    try {
        def serverSocket = new ServerSocket(0);
        System.out.println("listening on port: " + serverSocket.getLocalPort());
        //Do anything
        serverSocket.close()
    } catch (IOException ex) {
        System.err.println("no available ports");
    }
    

    If you need to found an available port in a range, check this post: How to find an available port in a range?