Testcontainers-java: Being able to set the container name like docker --name

Created on 26 Apr 2019  路  3Comments  路  Source: testcontainers/testcontainers-java

Hi, thx for such great framework. I just discovered it as I needed something like that.
I would like to be able to name the container other than the generated names docker does.
Right now I overrode it this way:

private static class MyGenericContainer<SELF extends MyGenericContainer<SELF>> extends GenericContainer<SELF> {
    MyGenericContainer(String dockerImageName, String containerName) {
      super(dockerImageName)
      this.containerName = containerName
    }

    @Override
    void close() {
      super.close()
    }
  }

Unfortunately it is set in at this line in GenericContainer.tryStart()

            containerName = containerInfo.getName();

Maybe there is a way to set it - in configure() but gets overriden still - and I have not found it.

Is there a way to do this? Is it something that can be added in future releases?

Thx, long life to TC :)
JH

Most helpful comment

Ok, I found the way to do this:

GenericContainer coordinatornew GenericContainer<>(DOCKER_IMAGE_NAME)
.withCreateContainerCmdModifier({ cmd -> cmd.withName('coordinator') })

This issue is now resolved, therefore closed.

All 3 comments

Ok, I found the way to do this:

GenericContainer coordinatornew GenericContainer<>(DOCKER_IMAGE_NAME)
.withCreateContainerCmdModifier({ cmd -> cmd.withName('coordinator') })

This issue is now resolved, therefore closed.

HI @itudoben, nice that you found out this approach.

Just wondering, what is your use case for naming the container? Keep in mind, a static name can lead to possible conflicts when creating the container, making it problematic in shared environments and in case of paralellization.

Just wondering, what is your use case for naming the container? Keep in mind, a static name can lead to possible conflicts when creating the container, making it problematic in shared environments and in case of paralellization.

A workaround for this is to add a random segment in your name, to have the best of both worlds: container names that more easily let you identify them, but still be reasonably unique. Something like this:

public class RedisContainer extends GenericContainer<RedisContainer> {
    private static final Random RANDOM = new Random();

    public RedisContainer() {
        withCreateContainerCmdModifier( cmd -> cmd.withName( "redis-" + ( RANDOM.nextInt() & Integer.MAX_VALUE ) ) );
    }
}
Was this page helpful?
0 / 5 - 0 ratings