2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018

07/10/2014: How find the published port of a Docker container in Java

After I spin up Accumulo in a Docker container, well-known ports (like 2181 for Zookeeper) are not well-known any more. The internal private port (i.e., 2181) is exposed as a different public port (i.e., 49143). Java program trying to connect to Accumulo must automatically find the public port numbers.
The java code below finds the public port for Zookeeper for a Docker container named "walt". I don't know why the slash is needed in the image name.

int wantedPublicPort = -1;

        String wantedContainerName = "/walt";
        int wantedPrivatePort = 2181;

        String dockerURL = "http://127.0.0.1:4243";
        String dockerUser = "medined";
        String dockerPassword = "XXXXX";
        String dockerEmail = "david.medinets@gmail.com";
        DockerClient docker = new DockerClient(dockerURL);
        docker.setCredentials(dockerUser, dockerPassword, dockerEmail);

        List<Container> containers = docker.listContainersCmd().exec();
        for (Container container : containers) {
            String[] names = container.getNames();
            for (String name : container.getNames()) {
                if (name.equals(wantedContainerName)) {
                    for (Container.Port port : container.getPorts()) {
                        if (port.getPrivatePort() == wantedPrivatePort) {
                            wantedPublicPort = port.getPublicPort();
                        }
                    }
                }
            }
        }

        System.out.println("Zookeeper Port: " + wantedPublicPort);

In order to use the DockerClient object, I added the following to my pom.xml:

gt;
    gt;com.github.docker-javagt;
    gt;docker-javagt;
    gt;0.9.0gt;
  gt;


subscribe via RSS