Skip to content

[Bug]: withStartupTimeout() changes the startup timeout of all containers that use the default wait strategy #12171

Open

Description

@aymenjamaaoui

Module

Core

Testcontainers version

2.0.5

Using the latest Testcontainers version?

Yes

Host OS

macOS 27.2.1

Host Arch

ARM

Docker version

Client:
 Version:           29.8.2
 API version:       1.56
 Go version:        go1.26.8
 Git commit:        7fc2dff
 Built:             Wed Sep 30 19:32:03 2026
 OS/Arch:           darwin/arm64
 Context:           desktop-linux

Server: Docker Desktop 4.94.0 (241994)
 Engine:
  Version:          29.8.2
  API version:      1.56 (minimum version 1.40)
  Go version:       go1.26.8
  Git commit:       8af9fe3
  Built:            Wed Sep 30 19:31:50 2026
  OS/Arch:          linux/arm64
  Experimental:     false
 containerd:
  Version:          v2.3.6
  GitCommit:        ee2735368117d2eb259779949d5e75cdafec9761
 runc:
  Version:          1.5.1
  GitCommit:        v1.5.1-0-g8f2685a4
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

What happened?

withStartupTimeout(Duration) on a container without its own wait strategy changes the startup timeout of all containers in the JVM that use the default wait strategy.

Expected: the timeout applies only to the container where it is set.
Actual: other containers get this timeout too. A short timeout on one container makes another container fail. The result depends on the order of tests in the JVM, so it looks like a flaky test in another class.

Reproduction. Put this test in core/src/test/java/org/testcontainers/containers/ and run
./gradlew :testcontainers:test --tests 'org.testcontainers.containers.DefaultWaitStrategyTimeoutTest':

package org.testcontainers.containers;

import org.junit.jupiter.api.Test;

import java.time.Duration;

class DefaultWaitStrategyTimeoutTest {

    @Test
    void startupTimeoutOfOneContainerDoesNotChangeOtherContainers() {
        // Never started. Only sets a short timeout for itself.
        new GenericContainer<>("alpine:3.17").withStartupTimeout(Duration.ofSeconds(2));

        // Default wait strategy (60 seconds). The port opens after 5 seconds.
        try (
            GenericContainer<?> slow = new GenericContainer<>("alpine:3.17")
                .withExposedPorts(8080)
                .withCommand("sh", "-c", "sleep 5; while true; do nc -l -p 8080; done")
        ) {
            slow.start();
        }
    }
}
  • On main (e16dca9): the test fails after about 3 seconds with ContainerLaunchException (log below).
  • Without the first line (new GenericContainer<>(...).withStartupTimeout(...)): the test passes after about 6 seconds.

Cause (links to main at e16dca9):

  1. DEFAULT_WAIT_STRATEGY is one static instance. Every container without waitingFor(...) points to it: the waitStrategy field and ContainerDef.
  2. getWaitStrategy() returns this shared instance.
  3. withStartupTimeout(Duration) calls getWaitStrategy().withStartupTimeout(...), so it changes the shared instance itself.

Relevant log output

org.testcontainers.containers.ContainerLaunchException: Container startup failed for image alpine:3.17
Caused by: org.testcontainers.containers.ContainerLaunchException: Could not create/start container
Caused by: org.testcontainers.containers.ContainerLaunchException: Timed out waiting for container port to open (localhost ports: [55831] should be listening)

Additional Information

A possible fix: give the container its own default strategy before changing the timeout. With this change, the test above passes:

public SELF withStartupTimeout(Duration startupTimeout) {
    if (getWaitStrategy() == DEFAULT_WAIT_STRATEGY) {
        waitingFor(Wait.defaultWaitStrategy());
    }
    getWaitStrategy().withStartupTimeout(startupTimeout);
    return self();
}

I can open a PR with this fix and the test if this direction is OK for you.

I found this while working on #12103: JdbcDatabaseContainer.withStartupTimeoutSeconds() must not change the shared instance either. #12103 is in draft until I fix it.

Activity

  1. Adrastopoulos commented on Nov 29, 2026

    @Adrastopoulos

    There is a second symptom of the shared default wait strategy: parallel starts can overwrite each other’s wait target even when neither container calls withStartupTimeout(). The current #12172 patch copies the strategy only from that setter, so it would leave this path unchanged.

    Environment: Testcontainers 2.0.5 (core, latest release), macOS ARM64 with Colima, Docker Engine 29.5.2, JDK 26.

    What happened?

    Expected: Two distinct GenericContainer instances can start in parallel in one JVM. Each port check uses the container it belongs to.

    Actual: A container that exposes 6379 can fail with Requested port (6379) is not mapped, even though Docker mapped its port and Redis was ready. In the reproduction, it looks up 6379 on the other container, which publishes 6380.

    In the 2.0.5 release, GenericContainer creates the static default, and ContainerDef stores that same object. AbstractWaitStrategy.waitUntilReady overwrites waitStrategyTarget, which HostPortWaitStrategy reads again while mapping exposed ports. If the overwrite happens just after the port lookup, the internal probe can instead check the wrong container and report a listening-port timeout.

    Relevant log output

    java.lang.IllegalArgumentException: Requested port (6379) is not mapped
    	at org.testcontainers.containers.ContainerState.getMappedPort(ContainerState.java:175)
    	at org.testcontainers.containers.wait.strategy.HostPortWaitStrategy.lambda$getInternalPorts$4(HostPortWaitStrategy.java:123)
        ...
    	at org.testcontainers.containers.wait.strategy.HostPortWaitStrategy.getInternalPorts(HostPortWaitStrategy.java:124)
    	at org.testcontainers.containers.wait.strategy.HostPortWaitStrategy.waitUntilReady(HostPortWaitStrategy.java:56)
    	at org.testcontainers.containers.wait.strategy.AbstractWaitStrategy.waitUntilReady(AbstractWaitStrategy.java:52)
    	at org.testcontainers.containers.GenericContainer.waitUntilContainerStarted(GenericContainer.java:904)
    	at org.testcontainers.containers.GenericContainer.tryStart(GenericContainer.java:487)
    
    [pool-1-thread-1] ERROR tc.redis:7.4.7-alpine - Log output from the failed container:
    1:M 29 Nov 2026 05:18:51.503 * Running mode=standalone, port=6379.
    1:M 29 Nov 2026 05:18:51.503 * Server initialized
    1:M 29 Nov 2026 05:18:51.503 * Ready to accept connections tcp
    

    Additional Information

    The reproduction starts two real containers on different ports. The latches control the wait order without changing either container. Save the files as pom.xml and Repro.java. Use a Docker environment configured for Testcontainers (tested with JDK 26).

    mvn -q dependency:build-classpath -Dmdep.outputFile=classpath.txt
    java -cp "$(cat classpath.txt)" Repro.java        # throws the exception above
    java -cp "$(cat classpath.txt)" Repro.java fresh  # both containers start

    On the environment above, the default waiter failed in all three runs and the fresh-waiter variant passed all three.

    Reproduction files

    pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0">
      <modelVersion>4.0.0</modelVersion>
      <groupId>example</groupId><artifactId>wait-target-repro</artifactId><version>1</version>
      <dependencies>
        <dependency><groupId>org.testcontainers</groupId><artifactId>testcontainers</artifactId><version>2.0.5</version></dependency>
        <dependency><groupId>org.slf4j</groupId><artifactId>slf4j-simple</artifactId><version>1.7.36</version></dependency>
      </dependencies>
    </project>

    Repro.java

    import java.util.List;
    import java.util.Set;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
    import org.testcontainers.containers.GenericContainer;
    import org.testcontainers.containers.wait.strategy.HostPortWaitStrategy;
    import org.testcontainers.containers.wait.strategy.Wait;
    
    class Repro {
        static final CountDownLatch FIRST_READ_PORTS = new CountDownLatch(1);
        static final CountDownLatch SECOND_ENTERED_WAIT = new CountDownLatch(1);
    
        static final class Redis extends GenericContainer<Redis> {
            final int port;
    
            Redis(int port, boolean fresh) {
                super("redis:7.4.7-alpine");
                this.port = port;
                withExposedPorts(port);
                withCommand("redis-server", "--port", Integer.toString(port));
                if (fresh) waitingFor(Wait.forListeningPort());
            }
    
            @Override public List<Integer> getExposedPorts() {
                var ports = super.getExposedPorts();
                // Pause after the first wait has read its own exposed ports.
                if (port == 6379 && StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
                        .getCallerClass() == HostPortWaitStrategy.class) {
                    FIRST_READ_PORTS.countDown();
                    await(SECOND_ENTERED_WAIT);
                }
                return ports;
            }
    
            @Override public Set<Integer> getLivenessCheckPortNumbers() {
                // The second wait has assigned its target by the time it gets here.
                if (port == 6380) SECOND_ENTERED_WAIT.countDown();
                return super.getLivenessCheckPortNumbers();
            }
        }
    
        public static void main(String[] args) throws Exception {
            boolean fresh = args.length > 0 && args[0].equals("fresh");
            try (var first = new Redis(6379, fresh); var second = new Redis(6380, fresh)) {
                var pool = Executors.newFixedThreadPool(2);
                try {
                    var startFirst = pool.submit(first::start);
                    while (!FIRST_READ_PORTS.await(100, TimeUnit.MILLISECONDS)) {
                        if (startFirst.isDone()) startFirst.get();
                    }
                    var startSecond = pool.submit(second::start);
                    startSecond.get(90, TimeUnit.SECONDS);
                    startFirst.get(90, TimeUnit.SECONDS);
                    System.out.println("Both containers started");
                } finally {
                    pool.shutdownNow();
                }
            }
        }
    
        static void await(CountDownLatch latch) {
            try {
                if (!latch.await(90, TimeUnit.SECONDS)) throw new AssertionError("Gate did not open");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new AssertionError(e);
            }
        }
    }

    As a workaround, each container can use .waitingFor(Wait.forListeningPort()). That keeps the same check and timeout but gives each container its own target. Would it make sense to give every container its own default at construction, so both symptoms are covered?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions