Skip to content

Advanced options

Container labels

To add a custom label to the container, use withLabel:

public GenericContainer containerWithLabel = new GenericContainer("alpine:3.6")
    .withLabel("key", "value");

Additionally, multiple labels may be applied together from a map:

private Map<String, String> mapOfLabels = new HashMap<>();
// populate map, e.g. mapOfLabels.put("key1", "value1");

public GenericContainer containerWithMultipleLabels = new GenericContainer("alpine:3.6")
    .withLabels(mapOfLabels);

Customizing the container

It is possible to use the docker-java API directly to customize containers before creation. This is useful if there is a need to use advanced Docker features that are not exposed by the Testcontainers API. Any customizations you make using withCreateContainerCmdModifier will be applied on top of the container definition that Testcontainers creates, but before it is created.

For example, this can be used to change the container hostname:

@Rule
public GenericContainer theCache = new GenericContainer<>("redis:3.0.2")
        .withCreateContainerCmdModifier(cmd -> cmd.withHostName("the-cache"));

... or modify container memory (see this if it does not appear to work):

@Rule
public GenericContainer memoryLimitedRedis = new GenericContainer<>("redis:3.0.2")
        .withCreateContainerCmdModifier(cmd -> cmd.withMemory((long) 8 * 1024 * 1024))
        .withCreateContainerCmdModifier(cmd -> cmd.withMemorySwap((long) 12 * 1024 * 1024));

Note

It is recommended to use this sparingly, and follow changes to the docker-java API if you choose to use this. It is typically quite stable, though.

For what is possible, consult the docker-java CreateContainerCmd source code.