Categories
Docker Java

Run Java TestContainers using an image from a private AWS ECR registry

In this short tutorial, we will see how to easily run a private docker image using Java TestContainers. We will use a private AWS ECR registry, but the code will work the same with any other private registry.

1) Needed parameters

First, you need to gather the following parameters:

String registry = "601730646169.dkr.ecr.us-west-2.amazonaws.com";
String image = "scalademopriv:2.0";
String username = "AWS";

String password = runCommand("aws ecr get-login-password --region us-west-2").get(0);

In my case, the AWS ECR registry password is obtained dynamically using the function runCommand:

static List<String> runCommand(String cmd) throws IOException {
    Process process = Runtime.getRuntime().exec(cmd);
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        return reader.lines().collect(Collectors.toList());
    }
}

How you obtain your password will depend on the docker registry you use.

2) Docker login

Then, you need to log into your docker registry, using following code:

String dockerLogin = "docker login --username " + username + " --password " + password + " " + registry;
runCommand(dockerLogin);

3) Instantiate the container, start it, and find the HTTP URL

In my case, the docker image is an HTTP service that runs on port 8080. To run the container and find its URL on the local machine, do:

DockerImageName imageName = DockerImageName.parse(registry + "/" + image);
GenericContainer<?> container = new GenericContainer<>(imageName).withExposedPorts(8080, 8080);
container.start();

String ip = container.getContainerIpAddress();
int mapped = container.getMappedPort(8080);

String url = "http://" + ip + ":" + mapped;

4) Full working code

That’s it for this tutorial, thank you for reading ! If you need help, please leave a reply below, we answer within 24 hours.

Leave a Reply

Your email address will not be published. Required fields are marked *